Lambda Expressions in C#

 Lambda Expressions in C#


Introduction:


Lambda expressions are nothing but an anonymous function. i.e. Lambda Expressions have no name, no access modifiers, and no return values. 


The syntax of Lambda expression is as below:


argument => expression;


=> is called Lambda operator and we read it as "goes to".

This is equivalent of writing as below:

static public returnType functionName(argument)
{
    expression;
}

Compare both these methods. The Lambda expression syntax has no name, no access modifiers, and no return values. 

If we have no arguments then, the syntax is 

    () => expression.

if we have multiple arguments, then 

    (arg1, arg2, ...) = > expression.


Example:

In the below example, which calculates square of a function, is a Lambda Expression. The second snippet uses normal function. 

Lambda Expressions:

Func<int,int> sqr =  x => x * x;
Console.WriteLine(sqr(5));


Normal Function:

Console.WriteLine(square(5));
static int square(int x)
{
    return x * x;
}


Hence, we use Lambda expression for convenience and readability.


Practical usage of Lambda Expression:

Lambda Expressions are very useful when we use Collections functions such as Find, FindAll.

These methods take Predicate as arguments, which is a function that contains a condition on which the collection function could apply.

If we don't use Lamda Expressions, the code looks a tad messy.

Consider the below example; I have created a list of integers.  And we shall use FindAll(). We can create the Predicate functions and pass it to FindAll() method.

List<int> numList = new List<int>()
{
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};

var listOfAbovefive = numList.FindAll(AboveFiveCond);



static bool AboveFiveCond(int i)
{
    return i > 5;
}


foreach (int num in listOfAbovefive)
{
    Console.WriteLine(num);
}

However, if we use Lambda Expression, the code looks cleaner.

List<int> numList = new List<int>()
{
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};

var listOfAbovefive = numList.FindAll(x => x > 5);



foreach (int num in listOfAbovefive)
{
    Console.WriteLine(num);
}