What Are Lambda Expressions?
Learn how to use lambda expressions with LINQ.
To work with LINQ, we need to be comfortable with delegates and lambda expressions. Let’s learn about them, starting with delegates.
What are delegates?
A delegate is a variable that references a method instead of a value or an object. In LINQ, Func
and Action
are the two built-in delegate types. We will be using Func
a lot with LINQ.
The difference between Func
and Action
is the return type of the method they point to. The Action
type references a void method. In other words, it references a method without return type. Conversely, Func
references a method with a return type.
Let’s look at some Func
and Action
declarations.
Action<Movie>
holds a method that receivesMovie
as a parameter and returns no values.Action
is a void method without any parameters.Func<Movie, string>
represents a method that gets aMovie
and returns astring
.Func<Movie>
doesn’t have any parameters and returnsMovie
.
When declaring Func
delegates, the last type inside <>
tells the return type of the method it accepts. The Action
delegates don’t have a return type. Then, the types inside <>
are the input parameter types.
Declaring a method that receives Func
or Action
Both Func
and Action
are helpful when working with higher-order functions. These are functions that take functions as parameters or return another function as a result.
If you’ve worked with JavaScript callbacks or Python decorators, you’ve worked with higher-order functions. Guess what methods are also higher-order functions: LINQ methods!
Let’s see how to declare a method that uses Func
or Action
.
To declare a method that uses Func
or Action
as an input parameter, we use them like regular parameters in the method declaration. Then, to use it inside the method’s body, we have to either call Invoke
on it or put parentheses next to the name passing the correct parameters.
Let’s see an example of a method that uses Func
. Let’s imagine we have a PrettyPrint()
method to print a movie out to the console. We’ll rely on a delegate to show the rating.
Get hands-on with 1400+ tech skills courses.