如何在 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学习者快速成长!