c#// Example 1: Lambda expression as a delegate
Func<int, int, int> add = (x, y) => x + y;
int result = add(5, 3); // result = 8
// Example 2: Lambda expression in a LINQ query
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0); // evenNumbers = [2, 4]
// Example 3: Lambda expression as an event handler
Button button = new Button();
button.Click += (sender, e) =>
{
Console.WriteLine("Button clicked!");
};
// Example 4: Lambda expression with multiple statements
Action<string> greet = name =>
{
string message = $"Hello, {name}!";
Console.WriteLine(message);
};
greet("John"); // Output: Hello, John!
In Example 1, a lambda expression is assigned to a delegate (Func<int, int, int> add
). The lambda expression (x, y) => x + y
takes two integer parameters and returns their sum. The delegate can then be invoked as a regular function, passing arguments to the lambda expression.
In Example 2, a lambda expression is used in a LINQ query to filter even numbers from a list of integers. The lambda expression n => n % 2 == 0
defines the filtering condition, where only numbers that satisfy the condition (divisible by 2) are selected.
In Example 3, a lambda expression is used as an event handler for a button's click event. When the button is clicked, the code within the lambda expression is executed, which in this case, writes a message to the console.
In Example 4, a lambda expression with multiple statements is used. The lambda expression name => { /* multiple statements */ }
takes a string parameter and prints a customized greeting message using string interpolation.
Lambda expressions provide a concise and expressive way to write functions or expressions without the need for explicitly defining a named method or a separate class. They are powerful constructs that enable functional programming concepts and improve the readability and maintainability of your code.
0 Comments