1.4. Lambda Expressions

Another new C# 3.0 feature is lambda expressions. This feature simplifies coding delegates and anonymous methods.

The argument to the Where<T> method we saw above is an example of a lambda expression:

Where(p => p.ID == 1)

Lambda expressions allow us to write functions that can be passed as arguments to methods, for example, to supply predicates for subsequent evaluation.

You could use code like that in Listing 1-4 to obtain the same result, but the lambda expression syntax is simpler.

Example 1-4. Alternative to Lambda Expression Syntax
Func<Person, bool> filter = delegate(Person p) { return p.ID == 1; };
var query = people
            .Where(filter)
            .Select(p => new { p.FirstName, p.LastName } );

ObjectDumper.Write(query);

Another ...

Get LINQ for Visual C# 2008 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.