如何使用 C# 中的 linq 擴充套件方法執行左外部聯接?


使用 INNER JOIN 僅將匹配元素包括在結果集中。不匹配的元素將從結果集中排除。

使用 LEFT OUTER JOIN 所有匹配的元素以及從左集合中所有不匹配的元素都包括在結果集中。

讓我們瞭解如何透過一個例子實現左外部聯接。考慮以下 Department 和 Employee 類。注意,Employee 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" }
      };
   }
}

更新於: 2020 年 12 月 5 日

1K+ 瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.