The Essential on lambda expressions in C # – Programming, Pseudocode Example, C# Programming Example
C# Console

The Essential on lambda expressions in C #

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

Here is an example of Lambda-statement

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:

Repeating the previous example, that of the calculation of the square, it is possible to write this piece of code instead:

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 :

Here’s another example, using the Average method:

 

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.

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.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.