C# Lambda Expressions
Lambda expressions in C# provide a concise syntax for creating anonymous functions. They are particularly useful for working with delegates, especially in scenarios involving LINQ queries, event handlers, and other functional programming patterns.
What are Lambda Expressions?
A lambda expression is a small block of code that takes parameters and returns a value. They are similar to methods but do not require a name and can be written inline where a delegate type is expected. The basic syntax of a lambda expression is:
(parameters) => expression;
or for a block body:
(parameters) => { statement(s); };
parameters: A comma-separated list of input parameters. You can omit the parentheses if there is only one parameter and its type is inferred.=>: The lambda operator, separating the parameters from the body of the expression.expression: A single expression that is executed and its result is returned.{ statement(s); }: A block of statements that are executed. If the lambda has a block body, it must explicitly use thereturnkeyword if it is intended to return a value.
Types of Lambda Expressions
Expression Lambdas
Expression lambdas consist of a single expression. The result of the expression is implicitly returned.
Example: Expression Lambda with Integer Input
This lambda takes an integer x and returns its square.
Func<int, int> square = x => x * x;
int result = square(5); // result will be 25
Example: Expression Lambda with Multiple Parameters
This lambda takes two integers a and b and returns their sum.
Func<int, int, int> add = (a, b) => a + b;
int sum = add(10, 20); // sum will be 30
Statement Lambdas
Statement lambdas consist of a block of statements enclosed in curly braces. You must explicitly use the return keyword if the lambda is expected to return a value.
Example: Statement Lambda for Output
This lambda takes a string and prints it to the console.
Action<string> greet = name => {
Console.WriteLine($"Hello, {name}!");
};
greet("World"); // Prints "Hello, World!"
Example: Statement Lambda Returning a Value
This lambda takes a number and returns a string indicating if it's even or odd.
Func<int, string> checkEvenOdd = number => {
if (number % 2 == 0) {
return $"{number} is even.";
} else {
return $"{number} is odd.";
}
};
string message = checkEvenOdd(7); // message will be "7 is odd."
Lambda Expressions and Delegates
Lambda expressions are often used to instantiate delegate types. The compiler infers the delegate type based on the lambda's signature and the context in which it is used.
Action: Delegates that do not return a value.Func<TResult>: Delegates that return a value of typeTResult.Func<T, TResult>: Delegates that take one parameter of typeTand return a value of typeTResult.- ...and so on for more parameters.
Lambda Expressions with LINQ
Lambda expressions are fundamental to Language Integrated Query (LINQ). They are used in methods like Where, Select, OrderBy, etc., to specify filtering, projection, and ordering criteria.
Example: Filtering a List with LINQ and Lambda
This example filters a list of numbers to find those greater than 5.
List<int> numbers = new List<int> { 1, 5, 8, 3, 10, 2 };
var greaterThanFive = numbers.Where(n => n > 5);
foreach (var num in greaterThanFive) {
Console.WriteLine(num); // Output: 8, 10
}
Key Benefits of Lambda Expressions
- Conciseness: Significantly reduces the amount of code needed for simple functions.
- Readability: Can make code more readable by expressing logic directly where it's used.
- Flexibility: Easily passed as arguments to methods that accept delegates.
- Anonymous Functions: Enables the creation of inline, unnamed functions.
Lambda expressions are a powerful feature in C# that enhance the expressiveness and efficiency of your code, especially when dealing with functional programming paradigms and data manipulation.