Archive

Archive for the ‘Development’ Category

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

January 23, 2013 Leave a comment

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