Lambda expressions were introduced in C # 3 (.NET 3.5). These expressions are used today everywhere in the code, to make LINQ queries, to make filters on lists, for delegates and events.
It is therefore essential to understand how this type of expression works.
What is a Lambda expression?
A lambda expression is an anonymous function that can contain expressions and instructions. This can be used to create delegates or expression tree types.
All expressions use the operator lambda => (reads “leads to”).
An expression is always made up of two parts:
the left side gives the input parameters (if any),
the side must give the instructions of the anonymous method.
Lambda expressions are used in two ways:
to create lambda-expression: this is an expression that is used to create expression trees (mostly used to execute instructions dynamically, ideal for creating data filters with Linq for example),
to create lambda instructions: this is the equivalent of a delegate in C # with a different syntax.
Examples
Here is an example of Lambda-expression
1 2 3 4 5 6 7 8 9 |
delegate int DelegateType(int i); public void Main() { DelegateType myDelegate = x => x*x; int square = myDelegate(5); // square is worth 25 } |
Here is an example of Lambda-statement
1 2 3 4 5 6 7 8 9 |
delegate void DelegateInstruction(string s); public void Main() { DelegateInstruction myFunc = str => { Console.WriteLine("Entree = {0}", str); }; myFunc("Hello"); // displays "Entree = Hello" } |
Use lambda expressions everyday
The basics
The .NET framework offers many methods that use lambda expressions through the Func type.
Func delegates are parameterized delegates that specify the input type (T) and the output type (TResult).
These delegates are very useful for encapsulating user-defined expressions to apply to a data source.
This delegate is defined like this:
1 2 3 |
public delegate TResult Func(TArg0 arg0) |
Repeating the previous example, that of the calculation of the square, it is possible to write this piece of code instead:
1 2 3 4 5 6 7 |
public void Main() { Func<int,int> myDelegate = x => x*x; int square = myDelegate(5); // square vaut 25 } |
Ok, this is an example is simple. But let’s go further. The framework offers many extension methods since the appearance of Linq.
The most used is undoubtedly Count which allows to return the number of elements of a collection.
This method supports several overloads, one of which proposes a parameter of the Func type, which makes it possible to specify a filtering expression.
Thanks to this mechanism, it is possible to count certain elements in particular.
Here is an example :
1 2 3 4 5 6 7 |
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; public void Main() { int pairs = numbers .Count(n => n % 2 == 0); } |
Here’s another example, using the Average method:
1 2 3 4 5 |
//Returns the average of the numbers in the //list (each of which is greater than 5) int average= numbers.Average(n => n>5); |
Applying consecutive filters
For example, consider a list of items we want to filter (for example, a user list).
Lambda expressions allow you to apply multiple filters to collections.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public void Main() { // delegate to keep only non-empty items Func filtreVide = s => !String.IsNullOrEmpty(s); // delegate to keep items that contain an "a" or "b" Func filtreLettres = s => s.Contains('a') || s.Contains('b'); List utilisateurs = new List(); utilisateurs.AddRange(new string[] { "", null, "pascal", "john" }); // 1st filter application IEnumerable resultat = utilisateurs.Where(filtreVide); // 2st filter application resultat = resultat.Where(filtreLettres); // result display foreach (var item in resultat) Console.WriteLine(item);} |
Conclusion
Lambda expressions are now widely used in the .NET framework. It is almost impossible to do without (many components use them).
I invite you to try and use these mechanisms.
To go further, you can also learn about the expression trees that can be used to create compiled methods on the fly to calculate expressions: See the Microsoft website.