Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

จะทำการรวมภายนอกด้านซ้ายโดยใช้วิธีการขยาย linq ใน C # ได้อย่างไร


ด้วย เข้าร่วมภายใน เฉพาะองค์ประกอบที่ตรงกันเท่านั้นที่จะรวมอยู่ในชุดผลลัพธ์ องค์ประกอบที่ไม่ตรงกันจะไม่รวมอยู่ในชุดผลลัพธ์

ด้วย LEFT OUTER JOIN องค์ประกอบที่ตรงกันทั้งหมด + องค์ประกอบที่ไม่ตรงกันทั้งหมดจากคอลเลกชันด้านซ้ายจะรวมอยู่ในชุดผลลัพธ์

ให้เราเข้าใจการใช้งาน Left Outer Join ด้วยตัวอย่าง พิจารณาชั้นเรียนของแผนกและลูกจ้างดังต่อไปนี้ ขอให้สังเกตว่า พนักงานแมรี่ไม่มีแผนกที่ได้รับมอบหมาย การรวมภายในจะไม่รวมบันทึกของเธอในชุดผลลัพธ์ ซึ่งจะเป็นการเข้าร่วมจากภายนอกด้านซ้าย

ตัวอย่าง

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