Free mag vol1 | Page 524

CHAPTER 12  LINQ TO OBJECTS List myCars = new List { "Yugo", "Aztec", "BMW" }; List yourCars = new List { "BMW", "Saab", "Aztec" }; // Get the common members. var carIntersect = (from c in myCars select c) .Intersect(from c2 in yourCars select c2); } Console.WriteLine("Here is what we have in common:"); foreach (string s in carIntersect) Console.WriteLine(s); // Prints Aztec and BMW. The Union() method, as you would guess, returns a result set that includes all members of a batch of LINQ queries. Like any proper union, you will not find repeating values if a common member appears more than once. Therefore, the following method will print out the values “Yugo”, “Aztec”, “BMW”, and “Saab”: static void DisplayUnion() { List myCars = new List { "Yugo", "Aztec", "BMW" }; List yourCars = new List { "BMW", "Saab", "Aztec" }; // Get the union of these containers. var carUnion = (from c in myCars select c) .Union(from c2 in yourCars select c2); } Console.WriteLine("Here is everything:"); foreach (string s in carUnion) Console.WriteLine(s); // Prints all common members. Finally, the Concat() extension method returns a result set that is a direct concatenation of LINQ result sets. For example, the following method prints out the results “Yugo”, “Aztec”, “BMW”, “BMW”, “Saab”, and “Aztec”: static void DisplayConcat() { 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 BMW Saab Aztec. foreach (string s in carConcat) Console.WriteLine(s); Removing Duplicates When you call the Concat()extension method, you could very well end up with redundant entries in the fetched result, which could be exactly what you want in some cases. However, in other cases, you might 464