Home  >  Article  >  Backend Development  >  How to perform a left outer join using linq extension methods in C#?

How to perform a left outer join using linq extension methods in C#?

WBOY
WBOYforward
2023-09-02 16:33:03885browse

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

When using INNER JOIN, only matching elements are included in the result set. Unmatched elements will be excluded from the result set.

When using LEFT OUTER JOIN, all unmatched elements in the set to the left of all matching elements will be included in the result set.

Let us understand with an example Implementation of left outer join. Consider the following Department and Employee classes. Note that employee Mary does not have a department assigned. The inner join will not include her records in the result set, while the left outer join will.

Example

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" }
      };
   }
}

The above is the detailed content of How to perform a left outer join using linq extension methods in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete