Free mag vol1 | Page 525

CHAPTER 12  LINQ TO OBJECTS want to remove duplicate entries in your data. To do so, simply call the Distinct() extension method, as seen here: static void DisplayConcatNoDups() { List myCars = new List { "Yugo", "Aztec", "BMW" }; List yourCars = new List { "BMW", "Saab", "Aztec" }; var carConcat = (from c in myCars select c) .Concat(from c2 in yourCars select c2); } // Prints: // Yugo Aztec BMW Saab Aztec. foreach (string s in carConcat.Distinct()) Console.WriteLine(s); LINQ Aggregation Operations LINQ queries can also be designed to perform various aggregation operations on the result set. The Count() extension method is one such aggregation example. Other possibilities include obtaining an average, max, min, or sum of values using the Max(), Min(), Average(), or Sum() members of the Enumerable class. Here is a simple example: static void AggregateOps() { double[] winterTemps = { 2.0, -21.3, 8, -4, 0, 8.2 }; // Various aggregation examples. Console.WriteLine("Max temp: {0}", (from t in winterTemps select t).Max()); Console.WriteLine("Min temp: {0}", (from t in winterTemps select t).Min()); Console.WriteLine("Avarage temp: {0}", (from t in winterTemps select t).Average()); Console.WriteLine("Sum of all temps: {0}", (from t in winterTemps select t).Sum()); } These examples should give you enough knowledge to feel comfortable with the process of building LINQ query expressions. While there are additional operators you have not yet examined, you will see further examples later in this text when you learn about related LINQ technologies. To wrap up your first look at LINQ, the remainder of this chapter will dive into the details between the C# LINQ query operators and the underlying object model.  Source Code The FunWithLinqExpressions project can be found under the Chapter 12 subdirectory. 465