Category Archives: .NET

C# Lambda Expressions: Quick Tutorial

In C#, there is a shortcut for anonymous methods called Lambda Expression. To understand Lambda, we first need to have a basic understanding of how delegates work.

Let’s assume we want to write a method that finds elements in a List<T> that match certain criterias. Those criterias can change between different calls of said method and for that we will need a delegate:

delegate bool matchesCriteria(int number);

static List<int> findInList(matchesCriteria doesMatchCriterias, List<int> list)
{
    var newList = new List<int>();

    foreach (var number in list)
    {
        if (doesMatchCriterias(number))
        {
            newList.Add(number);
        }
    }

    return newList;
}

We can call this method like this:

var outputList = findInList(delegate(int n) { return n < 5; }, list);

The first parameter is a new anonymous method that will be represented as 'doesMatchCriterias' in the 'findInList' method. What we are doing is basically creating a method that checks if a number is smaller than 5 and then returns true or false. If it's true, the 'findInList' method will add the number to a new list.

If we want to find all elements in a list that are not 9, we can use the exact same function since we've used a delegate:

var outputList = findInList(delegate(int n) { return n != 9; }, list);

Easy, right? Now a Lambda Expression helps us writing shorter anonymous delegates. Here is the last example written as a Lambda Expression:

var outputList = findInList(n => n != 9, list);

On the left-hand side of the Lambda Operator (=>) are the arguments for the delegate. The part on the right translates to a simple 'return n != 9'. We don't need the return keyword, because we only use one statement.

You can also use them in many methods provided by the .NET framework:

var outputList = list.FindAll(x => x < 6 && x != 15);

Summary

Lambda Expressions are shortcuts for anonymous methods and can be super useful. They were added in .NET 3.5 and can really clean up your code.