4.1. Lambda ExpressionsFrom the developer's perspective, lambda expressions in C# 3.0 are a straightforward simplification of anonymous methods. Whereas an anonymous method is an unnamed block of code, a lambda expression is an unnamed expression that evaluates to a single value. Given a value x and an expression f(x) to evaluate, the corresponding lambda expression is written x => f(x) For example, in C# 3.0 the previous call to FindAll with an anonymous method is significantly shortened by using a lambda expression: List<Doctor> inchicago = doctors.FindAll(x => x.City == "Chicago"); In this case, x is a doctor, and f(x) is the expression x.City == "Chicago", which evaluates to true or false. For readability, let's substitute d for x: List<Doctor> inchicago = doctors.FindAll(d => d.City == "Chicago"); Notice that this lambda expression matches the parameter and body of the anonymous method we saw earlier, minus the syntactic extras like {}. Lambda expressions are equivalent to anonymous methods that return a value when invoked, and are thus interchangeable. In fact, the compiler translates lambda expressions into delegate-based code, exactly as it does for anonymous methods. |