CHAPTER 10 DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS
Processing Arguments Within Multiple Statements
Our first lambda expression was a single statement that ultimately evaluated to a Boolean. However, as
you know, many delegate targets must perform a number of code statements. For this reason, C# allows
you to build lambda expressions using multiple statement blocks. When your expression must process
the parameters using multiple lines of code, you can do so by denoting a scope for these statements
using the expected curly brackets. Consider the following example update to our
LambdaExpressionSyntax() method:
static void LambdaExpressionSyntax()
{
// Make a list of integers.
List list = new List();
list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 });
// Now process each argument within a group of
// code statements.
List evenNumbers = list.FindAll((i) =>
{
Console.WriteLine("value of i is currently: {0}", i);
bool isEven = ((i % 2) == 0);
return isEven;
});
}
Console.WriteLine("Here are your even numbers:");
foreach (int evenNumber in evenNumbers)
{
Console.Write("{0}\t", evenNumber);
}
Console.WriteLine();
In this case, our parameter list (again, a single integer named i) is being processed by a set of code
statements. Beyond the calls to Console.WriteLine(), our modulo statement has been broken into two
code statements for increased readability. Assuming each of the methods we’ve looked at in this section
are called from within Main():
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Lambdas *****\n");
TraditionalDelegateSyntax();
AnonymousMethodSyntax();
Console.WriteLine();
LambdaExpressionSyntax();
Console.ReadLine();
}
we will find the following output:
394