CHAPTER 10 DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS
// ...becomes this anonymous method.
List evenNumbers = list.FindAll(delegate (int i)
{
return (i % 2) == 0;
});
Dissecting a Lambda Expression
A lambda expression is written by first defining a parameter list, followed by the => token (C#’s token for
the lambda operator found in the lambda calculus), followed by a set of statements (or a single
statement) that will process these arguments. From a very high level, a lambda expression can be
understood as follows:
ArgumentsToProcess => StatementsToProcessThem
Within our LambdaExpressionSyntax() method, things break down like so:
// "i" is our parameter list.
// "(i % 2) == 0" is our statement set to process "i".
List evenNumbers = list.FindAll(i => (i % 2) == 0);
The parameters of a lambda expression can be explicitly or implicitly typed. Currently, the
underlying data type representing the i parameter (an integer) is determined implicitly. The compiler is
able to figure out that i is an integer based on the context of the overall lambda expression and the
underlying delegate. However, it is also possible to explicitly define the type of each parameter in the
expression, by wrapping the data type and variable name in a pair of parentheses, as follows:
// Now, explicitly state the parameter type.
List evenNumbers = list.FindAll((int i) => (i % 2) == 0);
As you have seen, if a lambda expression has a single, implicitly typed parameter, the parentheses
may be omitted from the parameter list. If you want to be consistent regarding your use of lambda
parameters, you can always wrap the parameter list within parentheses, leaving us with this expression:
List evenNumbers = list.FindAll((i) => (i % 2) == 0);
Finally, notice that currently our expression has not been wrapped in parentheses (we have of
course wrapped the modulo statement to ensure it is executed first before the test for equality). Lambda
expressions do allow for the statement to be wrapped as follows:
// Now, wrap the expression as well.
List evenNumbers = list.FindAll((i) => ((i % 2) == 0));
Now that you have seen the various ways to build a lambda expression, how can we read this
lambda statement in human-friendly terms? Leaving the raw mathematics behind, the following
explanation fits the bill:
// My list of parameters (in this case, a single integer named i)
// will be processed by the expression (i % 2) == 0.
List evenNumbers = list.FindAll((i) => ((i % 2) == 0));
393