Lambda Expressions and Expression Trees

 

Many query operators allow the user to provide a function that performs filtering, projection, or key extraction. The query facilities build on the concept of lambda expressions, which provide developers with a convenient way to write functions that can be passed as arguments for subsequent evaluation. Lambda expressions are similar to CLR delegates and must adhere to a method signature defined by a delegate type. To illustrate this, we can expand the statement above into an equivalent but more explicit form using the Func delegate type:

Func<string, bool>   filter  = s => s.Length == 5;
Func<string, string> extract = s => s;
Func<string, string> project = s => s.ToUpper();

IEnumerable<string> query = names.Where(filter)
                                 .OrderBy(extract)
                                 .Select(project);

Lambda expressions are the natural evolution of anonymous methods in C# 2.0. For example, we could have written the previous example using anonymous methods like this:

Func<string, bool>   filter  = delegate (string s) {
                                   return s.Length == 5;
                               };

Func<string, string> extract = delegate (string s) {
                                   return s;
                               };

Func<string, string> project = delegate (string s) {
                                   return s.ToUpper();
                               };

IEnumerable<string> query = names.Where(filter)
                                 .OrderBy(extract)
                                 .Select(project);