Lambda Expressions and LINQ: Querying Data Efficiently are essential tools in C# for manipulating collections of data. Lambda expressions provide a concise way to represent anonymous functions, while LINQ (Language Integrated Query) offers a powerful and unified approach to querying data from various sources, such as collections, databases, and XML. Together, they enable developers to write expressive and efficient code for data processing.

Understanding Lambda Expressions

Lambda expressions are essentially anonymous functions that can be treated as data. They are a compact way to represent methods, especially when you need a simple function for a short period.

Syntax of Lambda Expressions

A lambda expression has the following basic syntax:

(input parameters) => expression or statement block

Examples of Lambda Expressions

Let's look at some examples to illustrate how lambda expressions work:

  1. A lambda expression with no parameters:

    Func<string> greet = () => "Hello, world!";
    Console.WriteLine(greet()); // Output: Hello, world!
    

    In this example, greet is a variable that holds a lambda expression. The lambda expression takes no input parameters (indicated by the empty parentheses ()) and returns the string "Hello, world!". Func<string> is a delegate type that represents a function that takes no arguments and returns a string.

  2. A lambda expression with one parameter:

    Func<int, int> square = x => x * x;
    Console.WriteLine(square(5)); // Output: 25
    

    Here, square is a lambda expression that takes one integer parameter x and returns its square. The type of x is inferred to be int based on the Func<int, int> delegate type, which represents a function that takes an integer and returns an integer.

  3. **A lambda expression with multiple parameters:**csharp

    Func<int, int, int> add = (x, y) => x + y;
    Console.WriteLine(add(3, 4)); // Output: 7
    

    In this case, add is a lambda expression that takes two integer parameters x and y and returns their sum. The parentheses around (x, y) are required when there are multiple input parameters.

  4. **A statement lambda:**csharp

    Action<string> greetByName = name =>
    {
        string greeting = "Hello, " + name + "!";
        Console.WriteLine(greeting);
    };
    greetByName("Alice"); // Output: Hello, Alice!
    

    This example demonstrates a statement lambda, which has a block of code enclosed in curly braces. Action<string> is a delegate type that represents a function that takes a string argument and returns void.

Using Lambda Expressions with Delegates

Lambda expressions are often used with delegates. A delegate is a type that represents a reference to a method. C# provides several built-in delegate types, such as Func and Action, which can be used with lambda expressions.

You can also define your own custom delegate types: