Table of Contents
1 - What is a lambda expression (Lambda expression)
As we saw in the post about delegates, lambda expressions are another way to represent anonymous methods using a special syntax.
Here we can see an example of an anonymous method that checks if the age is of majority:
delegate(int edad) { return edad >= 18 };
The same code can be represented using a Lambda expression as follows
edad => edad >= 18;
As you can see, the code has changed a bit and we are going to explain why.
- We removed the keyword delegate and the function parameter type (in this case the delegate).
- We include the lambda operator
=>
to indicate it is a Lambda expression. It must be included between the input parameter and the function body. - Finally, the compiler is smart enough to detect that parentheses or braces are not needed, so we can remove them.
1.1 - Multiple parameters in a Lambda Expression
Lambda expressions allow us to include multiple parameters if we enclose them in parentheses:
(edad, limiteEdad) => edad >= 18 && edad <= limiteEdad;
1.2 - Lambda expression with no parameters
Lambda expressions also allow us to omit parameters. For this, we simply include empty parentheses when declaring the expression.
() => Console.WriteLine("Expresión Lambda sin parámetros");
1.3 - Lambda expression with a body
Finally, we have the option to include a body with more than one line. To do this, just use braces, one to open and another to close: { ///Codigo }
edad => {
Console.WriteLine("comprobando la edad");
int edadMinima = 18;
return edad >= edadMinima;
}
As you can see, it is also possible to declare variables inside the body of a lambda expression.
2 - Using lambda expressions with delegates
A lambda expression can be assigned to delegates as we saw in the post about delegates: Func<in T, out TResult>
, Action<T>
, Predicate<in T>
.
Func<int, bool> mayorDeEdad = edad => edad >= 18;
Persona p = new Persona(){ Nombre = "Ivan", Edad = 27 };
bool esMayorDeEdad = mayorDeEdad(p.Edad); //return true
We can see that we can also call it as a method.
3 - Using lambda expressions in LINQ
The most common case for using lambda expressions is within LINQ
queries. LINQ is a query language for objects within C#. We will see a specific module dedicated to this, so I will not go into more detail now. I will leave the link here once I write that post.
For now, we just need to know that LINQ
contains an extension method thanks to the implementation of the IEnumerable<T>
interface, which is called .Where()
and accepts the delegate Func<T, bool>
, which means it will return true or false depending on what we provide as a predicate.
List<Persona> personas = new List<Persona>() { ... }
Func<int, bool> mayorDeEdad = edad => edad >= 18;
List<Persona> mayoresDeEdad = personas.Where( a=> mayorDeEdad(a.Edad));
Running the code, we can see how it filters all people who are not of legal age.
Conclusion
- Understanding and getting used to using lambda expressions is fundamental, as they are continuously used in our everyday work.
- The operator
=>
executes the expression, it does not assign a value. - The syntax is
parameters => function body
. - A lambda expression can have multiple parameters, or none at all.
- A lambda expression can be assigned to Func, Action, and Predicate delegates.
If there is any problem you can add a comment bellow or contact me in the website's contact form