Junior — Middle
Can you explain what a lambda expression is and how to apply it in programming?
sobes.tech AI
Answer from AI
A lambda expression in C# is an anonymous function that can contain an expression or a block of code and is used to create delegates or expression trees. Lambdas allow writing compact and readable code, especially when working with LINQ or event handlers.
Syntax:
(parameters) => expression
Example of using a lambda expression for filtering a list:
var numbers = new List<int> {1, 2, 3, 4, 5};
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
Here, n => n % 2 == 0 is a lambda that takes a parameter n and returns true if the number is even.
Lambdas can be either single-line or multi-line using curly braces:
Func<int, int, int> add = (x, y) => {
int result = x + y;
return result;
};
Thus, lambda expressions are a convenient way to describe small functions directly at the point of use.