Tuesday 6 October 2015

.Net Statement Lambda expressions and Expression Lambda expressions

Lambda expressions are two fold as Statement and Expression and they are got differ slightly b how we using curly braces in the code.

ie : If we are using the curly braces then it becomes a Statement lambda and vise versa.

Following is a small example to illustrate this. 


 
List<string> namesList = new List<string>();
IQueryable<string> query = namesList.AsQueryable();
namesList.Add("Priyal");
namesList.Add("Kasun");
namesList.Add("Praneeth");
namesList.Add("Primal");

string endsWithL1 = namesList.First(x => x.EndsWith("l"));
string endsWithL2= query.First(x => x.EndsWith("l"));
// endsWithL1 and endsWithL2 are now both 'two' as expected 
var foo1 = namesList.First(x => { return x.EndsWith("n"); }); //no error 
var   foo2 = query.First(x => { return x.EndsWith("n"); }); //error 
var  bar2 = query.First((Func<string, bool>)(x => { return x.EndsWith("n"); })); //no error 

Note that List.First expects a delegate and the IQueryable.First expects an expression.
This is why the foo1 gives a compile time error because we used curly braces and the it becomes a lambda statement. But we can can force the lambda to evaluate to a delegate as we did for the bar2.

No comments:

Post a Comment