Enumerable<T>的GroupJoin 方法和Jo的用法和區別
阿新 • • 發佈:2020-11-05
平時在專案中很多時候直接用 from s in list1 join s2 in list2 ....這樣的寫法,最近在專案中看到有同事用了Enumerable<T>的GroupJoin 方法和Join的用法,我也沒有深究二者的區別,今天就做了一個總結。
首先我們 先看join 的用法:
1 class Person 2 { 3 public string Name { get; set; } 4 } 5 6 class Pet 7 { 8 public string Name { get; set; } 9 public Person Owner { get; set; } 10 } 11 class Program 12 { 13 private static readonly int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 14 static void Main(string[] args) 15 { 28 Person magnus = new Person { Name = "Hedlund, Magnus" }; 29 Person terry = new Person { Name = "Adams, Terry" }; 30 Person charlotte = new Person { Name = "Weiss, Charlotte" }; 31 32 Pet barley = new Pet { Name = "Barley", Owner = terry }; 33 Pet boots = new Pet { Name = "Boots", Owner = terry }; 34 Pet whiskers = newPet { Name = "Whiskers", Owner = charlotte }; 35 Pet daisy = new Pet { Name = "Daisy", Owner = new Person() }; 36 37 List<Person> people = new List<Person> { magnus, terry, charlotte }; 38 List<Pet> pets = new List<Pet> { barley, boots, whiskers, daisy }; 65 var query = people.Join 66 (pets, 67 person => person, 68 pet => pet.Owner, 69 (person, pet) => 70 new 71 { 72 OwnerName = person.Name, 73 Pet = pet.Name 74 }); 75 76 foreach (var obj in query) 77 { 78 Console.WriteLine( 79 "{0} - {1}", 80 obj.OwnerName, 81 obj.Pet); 82 } 83 Console.ReadKey(); 84 }
我們斷點除錯的時候可以看到:
控制檯輸出的結果:
從上面的結果我們可以看出Join是一個inner join的結果,同時這個結果集是一個一維的平面結果集。
還是相同的資料,我們現在把程式碼改成GroupJoin的寫法如下:
var query = people.GroupJoin(pets, person => person, pet => pet.Owner, (person, petCollection) => new { OwnerName = person.Name, Pets = petCollection.Select(pet => pet.Name), Count = petCollection.Count() }); foreach (var obj in query) { // Output the owner's name. Console.WriteLine("{0}:", obj.OwnerName); // Output each of the owner's pet's names. foreach (string pet in obj.Pets) { Console.WriteLine(" {0}", pet); } } Console.ReadKey();
我們除錯的時候可以看到如下:
再看看輸出的結果
我們可以看出GroupJoin是一個left join的結果,是一個分組後的二維結果集