Linq101-Join
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 5 namespace Linq101 6 { 7 internal class Join 8 { 9 /// <summary> 10 /// This sample shows how to efficiently join elements of two sequences based on equality between key expressions over the two. 11 /// </summary> 12 public void Linq102() 13 { 14 string[] categories = { "Beverages", "Condiments", "Vegetables", "Dairy Products", "Seafood" }; 15 List<Data.Product> products = Data.GetProductList(); 16 17 var q = from c in categories 18 join p in products on c equals p.Category 19 select new { Category = c, p.ProductName }; 20 21 ObjectDumper.Write(q); 22 } 23 24 /// <summary> 25 /// Using a group join you can get all the products that match a given category bundled as a sequence. 26 /// </summary> 27 public void Linq103() 28 { 29 string[] categories = { "Beverages", "Condiments", "Vegetables", "Dairy Products", "Seafood" }; 30 List<Data.Product> products = Data.GetProductList(); 31 32 var q = from c in categories 33 join p in products on c equals p.Category into ps 34 select new { Category = c, Products = ps }; 35 36 foreach (var v in q) 37 { 38 Console.WriteLine(v.Category + ":"); 39 foreach (var p in v.Products) 40 { 41 Console.WriteLine(" " + p.ProductName); 42 } 43 } 44 } 45 46 /// <summary> 47 /// The group join operator is more general than join, as this slightly more verbose version of the cross join sample shows. 48 /// </summary> 49 public void Linq104() 50 { 51 string[] categories = { "Beverages", "Condiments", "Vegetables", "Dairy Products", "Seafood" }; 52 List<Data.Product> products = Data.GetProductList(); 53 54 var q = from c in categories 55 join p in products on c equals p.Category into ps 56 from p in ps 57 select new { Category = c, p.ProductName }; 58 59 foreach (var v in q) 60 { 61 Console.WriteLine(v.ProductName + ": " + v.Category); 62 } 63 } 64 65 /// <summary> 66 /// A so-called outer join can be expressed with a group join. A left outer joinis like a cross join, 67 /// except that all the left hand side elements get included at least once, even if they don't match any right hand side elements. 68 /// Note how Vegetablesshows up in the output even though it has no matching products. 69 /// </summary> 70 public void Linq105() 71 { 72 string[] categories = { "Beverages", "Condiments", "Vegetables", "Dairy Products", "Seafood" }; 73 List<Data.Product> products = Data.GetProductList(); 74 75 var q = from c in categories 76 join p in products on c equals p.Category into ps 77 from p in ps.DefaultIfEmpty() 78 select new { Category = c, ProductName = p == null ? "(No Products)" : p.ProductName }; 79 80 foreach (var v in q) 81 { 82 Console.WriteLine(v.ProductName + ": " + v.Category); 83 } 84 } 85 } 86 }