Free mag vol1 | Page 501

CHAPTER 12  LINQ TO OBJECTS Object and Collection Initialization Syntax Chapter 5 explored the role of object initialization syntax, which allows you to create a class or structure variable, and set any number of its public properties, in one fell swoop. The end result is a very compact (yet still easy on the eyes) syntax that can be used to get your objects ready for use. Also recall from Chapter 9, the C# language allows you to use a very similar syntax to initialize collections of objects. Consider the following code snippet, which uses collection initialization syntax to fill a List of Rectangle objects, each of which maintains two Point objects to represent an (x,y) position: List myListOfRects = new List { new Rectangle {TopLeft = new Point { X = 10, Y = 10 }, BottomRight = new Point { X = 200, Y = 200}}, new Rectangle {TopLeft = new Point { X = 2, Y = 2 }, BottomRight = new Point { X = 100, Y = 100}}, new Rectangle {TopLeft = new Point { X = 5, Y = 5 }, BottomRight = new Point { X = 90, Y = 75}} }; While you are never required to use collection/object initialization syntax, doing so results in a more compact code base. Furthermore, this syntax, when combined with implicit typing of local variables, allows you to declare an anonymous type, which is very useful when creating a LINQ projection. You’ll learn about LINQ projections later in this chapter. Lambda Expressions The C# lambda operator (=>) was fully explored in Chapter 10. Recall that this operator allows you to build a lambda expression, which can be used any time you invoke a method that requires a strongly typed delegate as an argument. Lambdas greatly simplify how you work with .NET delegates, in that they reduce the amount of code you have to author by hand. Recall that a lambda expression can be broken down into the following usage: ( ArgumentsToProcess ) => { StatementsToProcessThem } In Chapter 10, I walked you through how to interact with the FindAll() method of the generic List class using three different approaches. After working with the raw Predicate delegate and a C# anonymous method, you eventually arrived with the following (extremely concise) iteration that used the following lambda expression: static void LambdaExpressionSyntax() { // Make a list of integers. List list = new List(); list.AddRange(new int[] { 20, 1, 4, 8, 9, 4 Bғ