如何在 C# 中使用 linq 擴充方法執行左外連接?

WBOY
發布: 2023-09-02 16:33:03
轉載
862 人瀏覽過

如何在 C# 中使用 linq 扩展方法执行左外连接?

使用INNER JOIN時,結果集中只包含相符的元素。不匹配的元素將從結果集中排除。

使用LEFT OUTER JOIN時,所有匹配元素左側集合中的所有不匹配元素都將包含在結果集中.

讓我們透過一個範例來了解左外連接的實作。考慮以下 Department 和 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" }
      };
   }
}
登入後複製
#

以上是如何在 C# 中使用 linq 擴充方法執行左外連接?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!