C# Lambda Expressions
Lambda Expressions
A lambda expression is a short method without a name. You write it directly where you need it, often in one line.
Here is a normal method that multiplies a number by 2, and the same thing written as a lambda expression:
Example
// A normal method
static int MultiplyByTwo(int x)
{
return x * 2;
}
// The same as a lambda expression
x => x * 2
Read x => x * 2 as: "take x, and return x * 2".
- The parameter is on the left side of the arrow
=> - The value to return is on the right side
You don't need a name, a type, the return keyword or curly braces. A lambda is useful when you need a small piece of code in one place only.
Store a Lambda in a Variable
To store a lambda in a variable, use the type Func (short for function). Inside the < >, write the type of the parameter, and then the type of the return value:
Example
Func<int, int> multiplyByTwo = x => x * 2;
Console.WriteLine(multiplyByTwo(5)); // 10
Console.WriteLine(multiplyByTwo(8)); // 16
Func<int, int> means: the lambda takes an int and returns an int. You call the variable like a method: multiplyByTwo(5).
A lambda can have more than one parameter. Put the parameters inside parentheses. In Func, the last type is always the type of the return value:
Example
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(3, 4)); // 7
Lambdas Without a Return Value
If the lambda does something, but does not return a value (like a void method), use Action instead of Func. Inside the < >, write the parameter types:
Example
Action<string> greet = name => Console.WriteLine("Hello " + name);
greet("Liam");
greet("Jenny");
Here is a summary of the types used on this page:
| Type | The lambda takes | The lambda returns |
|---|---|---|
Func<int, int> | one int | an int |
Func<int, int, int> | two int values | an int |
Action<string> | one string | nothing |
Lambdas With Lists
Lambdas are often sent to other methods. Many List methods take a lambda that says what to do with each item.
FindAll() runs the lambda for each item. It returns a new list with all the items where the lambda returns true:
Example
List<int> scores = new List<int> { 8, 15, 3, 22, 11 };
List<int> highScores = scores.FindAll(s => s > 10);
foreach (int score in highScores)
{
Console.WriteLine(score);
}
The lambda s => s > 10 takes a score s, and returns true if the score is greater than 10. The parameter name is up to you. Here, s is short for score.
ForEach() runs the lambda once for each item in the list. It is a short way to write a foreach loop:
Example
List<string> cars = new List<string> { "Volvo", "BMW", "Ford" };
cars.ForEach(car => Console.WriteLine(car));
In the next chapter, you will use lambdas with LINQ, to filter, sort and count the items in a list.