C# Lambda Expression
In C#, a lambda expression is a concise way of defining an anonymous function. It is also known as a lambda function or lambda delegate. Lambda expressions are used in functional programming to create inline functions or delegates that can be passed as arguments to other functions. Lambda expressions are frequently used in LINQ queries to filter, sort, and project data.
The syntax for a lambda expression is as follows:
(parameters) => expression
Here, parameters
represent the input parameters of the function, and expression
represents the code that performs the function's computation. The =>
operator separates the parameters from the expression.
For example, the following lambda expression takes two integers as input and returns their sum:
(int x, int y) => x + y
This can be assigned to a delegate that has a signature matching the lambda expression:
Func<int, int, int> add = (x, y) => x + y;
Now the add
delegate can be called with two integers to get their sum:
int result = add(2, 3); // result == 5
Lambda expressions can also be used in LINQ queries. For example, the following LINQ query filters a list of integers to get only the even numbers:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; var evens = numbers.Where(n => n % 2 == 0);
In this case, the lambda expression (n => n % 2 == 0)
is used to define a filter function that takes an integer n
and returns true
if n
is even. The Where
method applies this filter function to each element in the list and returns a new list containing only the even numbers.