Lambda expressions in C#
Lambda expressions are a concise way to define anonymous functions in C#. They provide a compact syntax for creating delegates or expression trees. A Lambda expression consists of input parameters (if any), the Lambda operator (=>
), and the function body. The function body can be a single expression or a block of statements enclosed in curly braces.
The general syntax of a Lambda expression in C# is as follows:
(parameters) => expression
Here’s an example of a simple Lambda expression that adds two numbers:
Func<int, int, int> add = (a, b) => a + b;
In this example, we define a Lambda expression that takes two integers (a
and b
) as input parameters and returns their sum (a + b
). Func<int, int, int>
is a delegate type that represents a function that takes two integers as input and returns an integer as output. We assign our Lambda expression to a variable called add
, and we can now use this variable as if it were a regular function.
Lambda expressions are commonly used when working with higher-order functions or LINQ in C#. For instance, they can be used in LINQ’s Where
, Select
, OrderBy
, and other methods to specify filtering, projection, and ordering operations succinctly.
Here’s an example of using a Lambda expression with LINQ’s Where
method:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };List<int> evenNumbers = numbers.Where(num => num % 2 == 0).ToList();
In this example, we use a Lambda expression within the Where
method to filter out the even numbers from the numbers
list, and the result is stored in the evenNumbers
list.
Lambda expressions simplify the syntax of defining small, single-purpose functions, and they are particularly valuable in functional programming as they allow functions to be created directly at the call site without the need for explicit method declarations. They enhance code readability and maintainability, especially when working with collections and LINQ queries in C#.