DEV Community

Hootan Hemmati
Hootan Hemmati

Posted on

What is Lambda Expressions in C#

Lambda expressions are a shorthand way of defining anonymous functions in C#. They are used to create small, single-purpose functions that can be defined and called inline within your code. This makes your code more concise and easier to read, especially when dealing with functional programming concepts like LINQ.

Lambda expressions consist of three parts: the input parameters, the lambda operator, and the lambda body.

The input parameters are enclosed in parentheses and specify the input values to the function. If the function doesn't take any input values, the parentheses are left empty. For example, if you want to define a lambda expression that takes two integers as input and returns their sum, you would write:

(int x, int y) => x + y
Enter fullscreen mode Exit fullscreen mode

The lambda operator, represented by the symbol =>, separates the input parameters from the lambda body. The operator reads as "goes to", indicating that the input parameters are being used to create the lambda body.

The lambda body defines the behavior of the function. It can be a single expression or a block of statements enclosed in curly braces. For example, the lambda expression defined above returns the sum of the two input integers. If you wanted to define a lambda expression that calculated the average of a collection of integers, you could use a block of statements like this:

IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

Func<IEnumerable<int>, double> avg = nums => {
    int sum = 0;
    int count = 0;

    foreach (int num in nums)
    {
        sum += num;
        count++;
    }

    return (double)sum / count;
};
Enter fullscreen mode Exit fullscreen mode

This lambda expression takes a collection of integers as input and returns the average value as a double. The lambda body uses a loop to calculate the sum and count of the input numbers, and then divides the sum by the count to get the average.

Lambda expressions can be assigned to delegates, used as method arguments, or used in LINQ queries. When assigning a lambda expression to a delegate, you must specify the delegate type that matches the input and return types of the lambda expression. For example, the lambda expression defined above could be assigned to a delegate like this:

Func<IEnumerable<int>, double> avg = nums => {
    // some code here ...
};
Enter fullscreen mode Exit fullscreen mode

When using a lambda expression as a method argument, you must specify the delegate type that the method expects. For example, the Enumerable.Where method expects a Func delegate that takes a source element as input and returns a Boolean value indicating whether to include the element in the output sequence. You could use a lambda expression to filter a collection of integers to include only the even numbers like this:

IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

IEnumerable<int> evens = numbers.Where(num => num % 2 == 0);
Enter fullscreen mode Exit fullscreen mode

The lambda expression defined here takes a single integer as input and returns a Boolean value indicating whether the number is even. The Where method applies the lambda expression to each element in the collection and includes only those elements for which the lambda expression returns true.

In summary, Lambda expressions in C# provide a concise and readable way to define anonymous functions that can be used in a variety of contexts. They consist of input parameters, the lambda operator, and the lambda body, and can be assigned to delegates, used as method arguments, or used in LINQ queries.

Top comments (0)