Let??™s take a look at a few examples to make things more concrete before we
examine the details.
9.2 Simple examples using List
and events
When we look at extension methods in chapter 10, we??™ll use lambda expressions all the
time. Until then, List and event handlers give us the best examples. We??™ll start off
with lists, using automatically implemented properties, implicitly typed local variables,
and collection initializers for the sake of brevity. We??™ll then call methods that take delegate
parameters??”using lambda expressions to create the delegates, of course.
Listing 9.3 A concise lambda expression, bracketed for clarity
3 That??™s not to say it??™s impossible, however. Some languages allow closures to be represented as simple blocks
of code with a magic variable name to represent the common case of a single parameter.
236 CHAPTER 9 Lambda expressions and expression trees
9.2.1 Filtering, sorting, and actions on lists
If you remember the FindAll method on List, it takes a Predicate and
returns a new list with all the elements from the original list that match the predicate.
The Sort method takes a Comparison and sorts the list accordingly. Finally, the
ForEach method takes an Action to perform on each element. Listing 9.4 uses
lambda expressions to provide the delegate instance to each of these methods. The
sample data in question is just the name and year of release for various films.
Pages:
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453