What are lambda expressions in C#?


A lambda expression in C# describes a pattern. It has the token => in an expression context. This is read as “goes to” operator and used when a lambda expression is declared.

The following is an example showing how to use lambda expressions in C# −

Example

 Live Demo

using System;
using System.Collections.Generic;

class Demo {
   static void Main() {
      List<int> list = new List<int>() { 21, 17, 40, 11, 9 };
      int res = list.FindIndex(x => x % 2 == 0);
      Console.WriteLine("Index: "+res);
   }
}

Output

Index: 2

Above, we saw the usage of “goes to” operator to find the index of the even number −

list.FindIndex(x => x % 2 == 0);

The above example gives the following output.

Index: 2

Even number is at index 2 i.e. it is the 3rd element.

Updated on: 20-Jun-2020

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements