(lambda) the 11th letter of the Greek alphabet, has a common place in the mathematics world.
In the C# a lambda expression is an anonymous function that can contain expressions and statements.
Perhaps the most common use of lambdas is with enumerables. We also pass lambda expressions as arguments, for sorting or for searching in queries.
Anatomy of a lambda expression
1 |
x => x % 2 ! = 0 |
To the left, we have arguments. The “x” is just a name—we can use any valid name. The result is on the right.
Below we use FindIndex, which receives a Predicate method. We specify this as a lambda expression.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; using System.Collections.Generic; class Program { static void Main() { List<int> elements = new List<int>() { 1,2,3,4,5,6,7,8,9,10 }; // ... Find index of first odd element. int oddIndex = elements.FindIndex(x => x % 2 != 0); Console.WriteLine(oddIndex); } } |
1 2 3 |
x The argument name. => Separates argument list from result expression. x % 2 !=0 Returns true if x is not even. |
Anonymous functions
When using lambdas as anonymous functions the => operator separates the parameters to a method from its statements in the method’s body.
It is easy to confuse the => as a comparator operator but in the case of lambdas it is easier to think of the => as “goes to”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
using System; class Program { static void Main() { // Use implicitly typed lambda expression. Func<int, int> func1 = x => x + 1; // Use lambda expression with statement body. Func<int, int> func2 = x => { return x + 1; }; // Use formal parameters with expression body. Func<int, int> func3 = (int x) => x + 1; // Use parameters with a statement body. Func<int, int> func4 = (int x) => { return x + 1; }; // Use multiple parameters. Func<int, int, int> func5 = (x, y) => x * y; // Use no parameters in a lambda expression. Action func6 = () => Console.WriteLine(); // Invoke each of the lambda expressions we created. Console.WriteLine(func1.Invoke(1)); Console.WriteLine(func2.Invoke(1)); Console.WriteLine(func3.Invoke(1)); Console.WriteLine(func4.Invoke(1)); Console.WriteLine(func5.Invoke(2, 2)); func6.Invoke(); } } |
Output
2
2
2
2
4
Overview
Lambdas are made up of 3 parts:
Left side – This is the parameters. It can be empty. Sometimes it can be implicit (derived from the right).
Operator – operator => separates arguments from methods. It does not compare numbers
Right side – This is a statement list inside curly brackets with a return statement or an expression.