如何在C#中使用linq扩展方法执行左外部联接?
使用INNERJOIN 时,结果集中仅包含匹配的元素。不匹配的元素将从结果集中排除。
使用LEFTOUTERJOIN时 ,左集合中的所有匹配元素+所有非匹配元素都包含在结果集中。
让我们通过一个示例了解实现左外部联接。考虑以下部门和雇员类别。请注意,员工Mary没有分配部门。内部联接将不将她的记录包括在结果集中,左外部联接将在其中。
示例
static class Program{ static void Main(string[] args){ var result = Employee.GetAllEmployees() .GroupJoin(Department.GetAllDepartments(), e => e.DepartmentID, d => d.ID, (emp, depts) => new { emp, depts }) .SelectMany(z => z.depts.DefaultIfEmpty(), (a, b) => new{ EmployeeName = a.emp.Name, DepartmentName = b == null ? "No Department" : b.Name }); foreach (var v in result){ Console.WriteLine(" " + v.EmployeeName + "\t" + v.DepartmentName); } } } 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 = 1, Name = "IT"}, new Department { ID = 2, Name = "HR"}, }; } } public class Employee{ public int ID { get; set; } public string Name { get; set; } public int DepartmentID { get; set; } public static List<Employee> GetAllEmployees(){ return new List<Employee>(){ new Employee { ID = 1, Name = "Mark", DepartmentID = 1 }, new Employee { ID = 2, Name = "Steve", DepartmentID = 2 }, new Employee { ID = 3, Name = "Ben", DepartmentID = 1 }, new Employee { ID = 4, Name = "Philip", DepartmentID = 1 }, new Employee { ID = 5, Name = "Mary" } }; } }