LINQ左外连接

本文概述

  • LINQ左外部联接的语法
  • LINQ左外部联接的示例
在LINQ中, LEFT JOIN或LEFT OUTER JOIN用于返回左侧集合中的所有记录或元素, 并匹配集合右侧的元素。
在LINQ中, 要实现LEFT Join行为, 必须使用” INTO” 关键字和” DefaultfEmpty()” 方法。
LINQ左外部联接的语法 使用LINQ左外连接从集合中获取所有元素并与右集合中的元素匹配的语法。
var result = from e in objEmp1join d in objDept1on e.DeptId equals d.DepId into empDeptfrom ed in empDept.DefaultIfEmpty()select new{EmployeeName = e.Name, DepartmentName = ed == null ? "No Department" : ed.DepName}

根据上述语法, 我们使用into和DefaultfEmpty()方法来实现左外部联接, 以从” objEmp1″ , ” objDept1″ 集合中获取元素。
LINQ左外部联接的示例 这是使用LINQ左外部联接根据指定条件从集合中获取元素的示例。
using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp1{class Programme2{static void Main(string[] args){/*create an object of the class 'Department' and create a list with the added record*/List< Department> objDept1 = new List< Department> (){new Department{DepId=1, DepName="Software"}, new Department{DepId=2, DepName="Finance"}, new Department{DepId=3, DepName="Health"}}; /*create an object of the class 'Department'and create a list with the added record*/List< Employee> objEmp1 = new List< Employee> (){new Employee { EmpId=1, Name = "Akshay Tyagi", DeptId=1 }, new Employee { EmpId=2, Name = "Vishi Tyagi", DeptId=1 }, new Employee { EmpId=3, Name = "Arpita Rai", DeptId=2 }, new Employee { EmpId=4, Name = "Mani", DeptId =2}, new Employee { EmpId=5, Name = "Madhav Sai"}}; /*use Linq Query to fetch the information by using the join clause and check the department containing the employee or not */var result = from e in objEmp1join d in objDept1on e.DeptId equals d.DepId into empDeptfrom ed in empDept.DefaultIfEmpty()select new{EmployeeName = e.Name, DepartmentName = ed == null ? "No Department" : ed.DepName}; foreach (var item in result){Console.WriteLine(item.EmployeeName + "\t | " + item.DepartmentName); }Console.ReadLine(); }}class Department{public int DepId { get; set; }public string DepName { get; set; }}class Employee{public int EmpId { get; set; }public string Name { get; set; }public int DeptId { get; set; }}}

【LINQ左外连接】从上面的示例中, 我们通过在LINQ中使用左外部联接从” objEmp1″ 和” objDept1″ 集合中获取元素, 并且在这里我们指定了检查该员工是否有部门的条件。如果部门未映射, 则将从条件中获取” 无部门” 。
输出
LINQ左外连接

文章图片

    推荐阅读