Junior — Middle
Can you explain what a lambda expression is in programming and how it is used?
sobes.tech AI
Answer from AI
A lambda expression in programming is a compact way to describe an anonymous function, that is, a function without a name, which can be passed as a parameter or used for concise code writing.
In C#, lambda expressions are often used to create delegates or LINQ expressions. They have the syntax:
(parameters) => expression
or
(parameters) => { statements }
Example of usage:
// List of numbers
List<int> numbers = new List<int> {1, 2, 3, 4, 5};
// Using lambda to filter even numbers
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach(var num in evenNumbers)
{
Console.WriteLine(num); // Will output 2 and 4
}
Here, n => n % 2 == 0 is a lambda expression that takes a parameter n and returns true if the number is even. This allows writing more expressive and concise code.