LINQ:Group Join
一、数据准备
public class Employee { public int ID { get; set; } public string Name { get; set; } public int AddressId { get; set; } public int DepartmentId { get; set; } public static List<Employee> GetAllEmployees() { return new List<Employee>() { new Employee { ID = 1, Name = "张三", AddressId = 1,DepartmentId=10}, new Employee { ID = 2, Name = "李四", AddressId =2,DepartmentId=20}, new Employee { ID = 3, Name = "王五", AddressId = 0,DepartmentId=0}, new Employee { ID = 4, Name = "钱六", AddressId = 0,DepartmentId=0}, new Employee { ID = 5, Name = "郑七", AddressId = 5,DepartmentId=0}, new Employee { ID = 6, Name = "苏八", AddressId = 6,DepartmentId=10} }; } }
public class Department { public int ID { get; set; } public string Name { get; set; } public static List<Department> GetAllDepartments() { return new List<Department>() { new Department { ID = 10, Name = "IT"}, new Department { ID = 20, Name = "HR"}, new Department { ID = 30, Name = "Sales" }, }; } }
二、Group Join
1.法一Query Syntax
var GroupJoinQS = from dept in Department.GetAllDepartments() join emp in Employee.GetAllEmployees() on dept.ID equals emp.DepartmentId into EmployeeGroups select new { dept, EmployeeGroups }; //Outer Foreach is for all department foreach (var item in GroupJoinQS) { Console.WriteLine("Department :" + item.dept.Name); //Inner Foreach loop for each employee of a department foreach (var employee in item.EmployeeGroups) { Console.WriteLine(" EmployeeID : " + employee.ID + " , Name : " + employee.Name); } }
2.法二Method Syntax
var GroupJoinMethod = Department.GetAllDepartments() .GroupJoin( Employee.GetAllEmployees(), dept => dept.ID, emp => emp.DepartmentId, (dept, emp) => new { dept, emp } ); foreach (var item in GroupJoinMethod) { Console.WriteLine("Department :" + item.dept.Name); //Inner Foreach loop for each employee of a department foreach (var employee in item.emp) { Console.WriteLine(" EmployeeID : " + employee.ID + " , Name : " + employee.Name); } }
官方解释
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);
三、测试结果
注意上面虽然Sales这个部门对应的Employee为空,但还是显示出来,而且发现,显示的结果是分组好的。(其实是LEFT JOIN,只是LEFT JOIN没有分组,可以这么理解吗?)
四、Group Join, Inner Join和Left Join之间的区别
1. 与上文的Inner Join对比?
注意Inner Join是没分组的,所以foreach只有一层,而且inner join是不会显示出Sales这个部门,结果如下:
2. 与下文Left Join对比?
注意Left Join也是没分组的,所以foreach只有一层,会显示Sales这个部门,但一定一定要注意判断为空
五、参考网址
https://dotnettutorials.net/lesson/linq-group-join/
本文来自博客园,转载请注明原文链接:https://www.cnblogs.com/keeplearningandsharing/p/16625086.html