[C#]使用GroupJoin将两个关联的集合进行分组
本文为原创文章、源代码为原创代码,如转载/复制,请在网页/代码处明显位置标明原文名称、作者及网址,谢谢!
本文使用的开发环境是VS2017及dotNet4.0,写此随笔的目的是给自己及新开发人员作为参考,
首先,对于GroupJoin的用法说明如下:
语法:
public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>( this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector )
参数说明:
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 通过对两个序列执行分组的联接获得的。
参数类型:
TOuter
第一个序列中的元素的类型。
TInner
第二个序列中的元素的类型。
TKey
键选择器函数返回的键的类型。
TResult
结果元素的类型。
参考链接如下:
例程:
using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApp33 { class Program { static void Main(string[] args) { GroupJoinEx(); } static void GroupJoinEx() { Person p1 = new Person() { Name = "ABC", Age = 18 }; Person p2 = new Person() { Name = "EFG", Age = 19 }; Person p3 = new Person() { Name = "LMN", Age = 20 }; Person p4 = new Person() { Name = "XYZ", Age = 21 }; List<Person> pList = new List<Person> { p1, p2, p3, p4 }; Department d1 = new Department() { Name = "A1", Employee = p1 }; Department d2 = new Department() { Name = "A2", Employee = p2 }; Department d3 = new Department() { Name = "A3", Employee = p1 }; Department d4 = new Department() { Name = "B1", Employee = p3 }; Department d5 = new Department() { Name = "B2", Employee = p4 }; Department d6 = new Department() { Name = "B3", Employee = p4 }; List<Department> dList = new List<Department> { d1, d2, d3, d4, d5, d6 }; var result = pList.GroupJoin(dList, person => person, department => department.Employee, (person, departments) => new { Person = person, Department = departments.Select(d => d) }); foreach(var item1 in result) { Console.Write($"Name:{item1.Person} & "); foreach(var item2 in item1.Department) { if(item1.Department.First() == item2) Console.Write($"Department:{item2} "); else Console.Write($"{item2} "); } Console.WriteLine(); } } } class Person { public string Name { set; get; } public int Age { set; get; } public override string ToString() { return $"{Name},{Age}"; } } class Department { public string Name { set; get; } public Person Employee { set; get; } public override string ToString() { return $"{Name}"; } } }
输出结果: