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); };

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.

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

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.