>  기사  >  백엔드 개발  >  C#에서 linq 확장 메서드를 사용하여 왼쪽 외부 조인을 수행하는 방법은 무엇입니까?

C#에서 linq 확장 메서드를 사용하여 왼쪽 외부 조인을 수행하는 방법은 무엇입니까?

WBOY
WBOY앞으로
2023-09-02 16:33:03885검색

如何在 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으로 문의하시기 바랍니다. 삭제