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, Cities = c });

 

posted @ 2020-09-18 16:39  超级驼鹿  阅读(249)  评论(0编辑  收藏  举报
/*