Lambda Expressions
List.Find(Predicate match)
Suppose you have a list of names and want to find every person whose surname is "Johnson." List<T> contains a method called Find(Predicate<T> match), which (as you can see) takes a predicate and returns every element that matches it. In C# 2.0, you could write your query as follows:
names.Find(IsJohnson);
public static bool IsJohnson(string name)
{
return name.Contains("Johnson");
}
Or, using anonymous methods, you can write:
names.Find(delegate(string name) { return name.Contains("Johnson"); });
Both get the job done, but they are clunky to read. With lambda expressions in C# 3.0, you would write the following:
names.Find((string name) => name.Contains("Johnson"));
Which is a lot easier to read than the anonymous delegate. You can take it one step further by getting rid of the variable type declaration:
names.Find(name => name.Contains("Johnson"));
Lambda expressions are smart enough to infer variable types, so there's no need to explicitly declare the type.