1. 程式人生 > 實用技巧 >Linq查詢 Join與GroupJoin

Linq查詢 Join與GroupJoin

用處:當需要將兩張表根據某個屬性進行合併

1.兩張表結構

class Person
{
    public int CityID { set; get; }
    public string pName { set; get; }
}
class City
{
    public int CityNum{ set; get; }
    public string cName { set; get; }
}

2.由兩個類構成的資料

Person[] persons = new Person[]
    {
        new Person{ CityID = 1, pName = "
ABC" ,Age = 22 }, new Person{ CityID = 1, pName = "EFG" ,Age = 21 }, new Person{ CityID = 2, pName = "HIJ" ,Age = 19 }, new Person{ CityID = 3, pName = "KLM" ,Age = 19 }, new Person{ CityID = 3, pName = "NOP" ,Age = 20 }, new Person{ CityID = 4, pName = "QRS" ,Age = 23 },
new Person{ CityID = 5, pName = "TUV" ,Age = 19 } }; City[] cities = new City[] { new City{ CityNum = 1, cName = "Guangzhou" }, new City{ CityNum = 2, cName = "Shenzhen" }, new City{ CityNum = 3, cName = "Beijing" } };

3. 當使用 Join , CityID 沒有和 CityNum 對應的時候 將被忽略,返回的 persons 少於原來的條數

var result =  persons.Join(cities, p => p.CityID, c => c.CityNum, (p, c) => new { PName = p.pName, Age = p.Age, CName = c.cName});

4.當使用 GroupJoin, CityID 沒有和 CityNum 對應的時候仍然保留,返回的 persons 還是原來的條數,只是部分欄位為空

var result = persons.GroupJoin(cities, p => p.CityID, c => c.CityNum, (p, c) => new { PName = p.pName, Age = p.Age, CName = c.cName });