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.

Func<TResult>
Func<T,TResult>
Func< T1,T2,TResult>
Func< T1,T2,T3,TResult>
Func< T1,T2,T3,T4,TResult> 

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

model.Users.Count(u => u.UserName == username);

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:

Func<User,bool> userExpression = (u => u.UserName == username);
model.Users.Count(userExpression);

If your lambda uses say 2 input types your code would look something like this:

Func<User,Ticket,bool> userExpression =
     ((u,t) => u.UserName == username && t.UserID == u.UserID ); 

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

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Powered by Sweet Captcha
Verify your real existence,
Drag the juice to the glass
  • captcha
  • captcha
  • captcha
  • captcha

   
© 2011 Andy Gibson
Header image courtesy of Don Solo
Suffusion theme by Sayontan Sinha