C# 3.0 added lambdas to the language syntax. I wont go into details as to what those are as there is pleanty of information on the web, what I will show is how you can assign a lambda to a variable for later use.
I do a lot of work with LINQ and the Entity Framework and as such lambdas come in very useful when using LINQ expressions (I am not a fan of the query syntax), however it is sometimes useful to reuse a lambda. A lamda is simply a delegate that has a number of different prototypes all under Func.
[source:C#]
Func<TResult>
Func<T,TResult>
Func< T1,T2,TResult>
Func< T1,T2,T3,TResult>
Func< T1,T2,T3,T4,TResult>ÂÂ
[/source]
All of the lambdas take a result type and each varient adds an additional input type.ÂÂ
How does this help us save a lamda? Well lets take an example piece of code
[source:C#]
model.Users.Count(u => u.UserName == username);
[/source]
Here I am searching through the Users collection for any users which have UserName equal to the username variable. The input type for the lamda is User as Users is actually an ObjectQuery<User> object, the return type is bool as I am comparing 2 values and returning the result.
To store this lamda I do the following:
[source:C#]
Func<User,bool> userExpression = (u => u.UserName == username);
model.Users.Count(userExpression);
[/source]
If your lambda uses say 2 input types your code would look something like this:
[source:C#]
Func<User,Ticket,bool> userExpression =
   ((u,t) => u.UserName == username && t.UserID == u.UserID );ÂÂ
[/source]
The main difference here being that the list of input types must be wrapped in parenthesis (u,t) followed by the => operator.
For more information on lamdas have a look at this InformIT Article


