Join
两个互相Join的集合顺序随意,不过后面的key ,以及返回结果函数 参数的顺序要和join的顺序一致
// 初始化员工信息
var persons = new[] { new Person { Id = 1, Name = "张三" }, new Person { Id = 2, Name = "李四" }, new Person { Id = 3, Name = "王二" } };
// 初始化员工的联系方式
var contactInfos = new[]
{
new ContactInformation {PersonId = 1, Address = "上海", PhoneNumber = "001-00001"},
new ContactInformation {PersonId = 2, Address = "北京", PhoneNumber = "002-00002"},
new ContactInformation {PersonId = 3, Address = "广州", PhoneNumber = "003-00003"},
new ContactInformation {PersonId = 1, Address = "深圳", PhoneNumber = "004-00004"}
};
//var joinResult = contactInfos.Join(persons, contactInfo => contactInfo.PersonId, person => person.Id, (information, person) => new
//{
// Name = person.Name,
// PhoneNumber = information.PhoneNumber,
// Address = information.Address
//});
var joinResult = persons.Join(contactInfos, person => person.Id, contactInfo => contactInfo.PersonId, (person,information ) => new
{
Name = person.Name,
PhoneNumber = information.PhoneNumber,
Address = information.Address
});
foreach (var item in joinResult)
{
Console.WriteLine($"姓名:{item.Name},电话:{item.PhoneNumber},地址:{item.Address}");
}
姓名:张三,电话:001-00001,地址:上海
姓名:张三,电话:004-00004,地址:深圳
姓名:李四,电话:002-00002,地址:北京
姓名:王二,电话:003-00003,地址:广州
GroupJoin 用第一个集合的键 去 匹配所有第二个集合的键(可能多个)
参数说明:
outer Type: System.Collections.Generic.IEnumerable<TOuter> 要联接的第一个序列。 inner Type: System.Collections.Generic.IEnumerable<TInner> 要与第一个序列联接的序列。 outerKeySelector Type: System.Func<TOuter, TKey> 用于从第一个序列的每个元素提取联接键的函数。 innerKeySelector Type: System.Func<TInner, TKey> 用于从第二个序列的每个元素提取联接键的函数。 resultSelector Type: System.Func<TOuter, IEnumerable<TInner>, TResult> 用于从第一个序列的元素和第二个序列的匹配元素集合中创建结果元素的函数。 返回值 Type: System.Collections.Generic.IEnumerable<TResult> IEnumerable<T> ,其中包含类型的元素 TResult 通过对两个序列执行分组的联接获得的。
// 初始化员工信息
var persons = new[] { new Person { Id = 1, Name = "张三" }, new Person { Id = 2, Name = "李四" }, new Person { Id = 3, Name = "王二" } };
// 初始化员工的联系方式
var contactInfos = new[]
{
new ContactInformation {PersonId = 1, Address = "上海", PhoneNumber = "001-00001"},
new ContactInformation {PersonId = 2, Address = "北京", PhoneNumber = "002-00002"},
new ContactInformation {PersonId = 3, Address = "广州", PhoneNumber = "003-00003"},
new ContactInformation {PersonId = 1, Address = "深圳", PhoneNumber = "004-00004"}
};
var groupJoinResult = persons.GroupJoin(contactInfos, person => person.Id, contactInfo => contactInfo.PersonId, (person, infos) => new
{
Name = person.Name,
Phones = string.Join(",", infos.Select(x => x.PhoneNumber))
});
foreach (var item in groupJoinResult)
{
Console.WriteLine($"姓名:{item.Name},电话:{item.Phones}");
}
姓名:张三,电话:001-00001,004-00004
姓名:李四,电话:002-00002
姓名:王二,电话:003-00003