[轉]C# List.Join方法


最近在研究C#泛型集合的時候發現了List.Join方法,這個方法與C#中的string.Join方法還有js中的join方法不一樣,不是根據分隔符鏈接字符串,而是根據兩個對象關聯起來生成新的數據。

 

List.Join方法更像SQL 中的JOIN連接,該方法是根據兩個泛型集合之間的關系,將這兩個集合合並后獲取新的集合。而SQL的JOIN 則是根據兩個或多個表中的列之間的關系,從這些表中查詢數據。(PS:具體可以參考微軟官方MSDN的說明)

這是整理后的官方范例代碼(代碼在控制台應用程序中運行):

    /*寵物主人*/ class Person { public string Name { get; set; } } /*寵物*/ class Pet { public string Name { get; set; } public Person Owner { get; set; } } static void Main(string[] args) { /*寵物主人*/ Person magnus = new Person { Name = "Hedlund, Magnus" }; Person terry = new Person { Name = "Adams, Terry" }; Person charlotte = new Person { Name = "Weiss, Charlotte" }; /*寵物*/ Pet barley = new Pet { Name = "Barley", Owner = terry }; Pet boots = new Pet { Name = "Boots", Owner = terry }; Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte }; Pet daisy = new Pet { Name = "Daisy", Owner = magnus }; /*寵物主人列表集合*/ List<Person> people = new List<Person> { magnus, terry, charlotte }; /*寵物列表集合*/ List<Pet> pets = new List<Pet> { barley, boots, whiskers, daisy }; /* * Create a list of Person-Pet pairs where * each element is an anonymous type that contains a * Pet's name and the name of the Person that owns the Pet. * 創建一個包含 "主人-寵物" 這樣對應對象的列表 * ,其中每個對象元素都是包含寵物名字和寵物主人名字的匿名類型 */ var query = people.Join(pets, person => person, pet => pet.Owner , (person, pet) => new { OwnerName = person.Name, Pet = pet.Name }); /*循環輸出最終結果 格式:寵物主人名-寵物名*/ foreach (var obj in query) { Console.WriteLine("{0} - {1}", obj.OwnerName, obj.Pet); } Console.ReadKey(); }

最終控制台輸出的結果如下:

輸出結果

下面使用SQL語句JOIN連接查詢,從而模擬出List.Join方法的同等效果,其中有Person和Pet這兩張表,根據Pet寵物表的PID關聯Person寵物主人表的ID。

Person表數據如下:

id Name
1 Hedlund, Magnus
2 Adams, Terry
3 Weiss, Charlotte

Pet表數據如下:

id Name pid
1 Daisy 1
2 Barley 2
3 Boots 2
4 Whiskers 3

查詢語句如下:

SELECT P.Name+' - '+PT.Name AS '寵物主人 - 寵物名稱' FROM Person AS P JOIN Pet AS PT ON P.Id=PT.PID

查詢結果如下:

寵物主人 - 寵物名稱
Hedlund, Magnus - Daisy
Adams, Terry - Barley
Adams, Terry - Boots
Weiss, Charlotte - Whiskers

最終結果和上面使用List.Join方法獲取的一模一樣吧。


作者:十有三

出處:https://shiyousan.com/post/635434860251469582

版權聲明:本文采用知識共享許可協議:署名-相同方式共享 4.0 國際(CC BY-SA 4.0)。歡迎轉載本文,轉載請聲明出處或保留此段聲明。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM