Home > Development > Lambda IQueryable – ‘statement lambda’ vs ‘expression lambda’

Lambda IQueryable – ‘statement lambda’ vs ‘expression lambda’

Great article http://www.codeproject.com/Articles/47887/C-Delegates-Anonymous-Methods-and-Lambda-Expressio

There is an important difference between using braces and not using them. When you use them, you are creating a ‘statement lambda’, otherwise it is ‘expression lambda’. Statement lambdas can execute multiple statements (hence the need for braces) and can not create expression trees. You will probably only run into this problem when working with the IQueryable interface. The example below shows the problem.

List<string> list = new List<string>(); 
IQueryable<string> query = list.AsQueryable(); 
list.Add("one"); 
list.Add("two"); 
list.Add("three"); 
 
string foo = list.First(x => x.EndsWith("o")); 
string bar = query.First(x => x.EndsWith("o")); 
// foo and bar are now both 'two' as expected 
foo = list.First(x => { return x.EndsWith("e"); }); //no error 
bar = query.First(x => { return x.EndsWith("e"); }); //error 
bar = query.First((Func<string,bool>)(x => { return x.EndsWith("e"); })); //no error 

The second assignment of bar fails at compile time. This is because IQueryable.First expects an expression as a parameter whereas the extension method List.First expects a delegate. You can force the lambda to evaluate to a delegate (and use the First’s method overload) by making a cast as I did in the third assignment to bar.

Advertisements
Categories: Development
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: