📜  LINQ左外部联接

📅  最后修改于: 2021-01-06 05:39:01             🧑  作者: Mango

LINQ左外连接

在LINQ中, LEFT JOINLEFT OUTER JOIN用于返回左侧集合中的所有记录或元素,并匹配集合右侧的元素。

在LINQ中,要实现LEFT Join行为,必须使用“ INTO ”关键字和“ DefaultfEmpty() ”方法。

LINQ左外部联接的语法

使用LINQ左外连接从集合中获取所有元素并与右集合中的元素匹配的语法。

var result = from e in objEmp1
join d in objDept1
on e.DeptId equals d.DepId into empDept
from 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 objDept1 = new List()
        {
        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*/
           ListobjEmp1 = new List()
            {
            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 objEmp1
            join d in objDept1
            on e.DeptId equals d.DepId into empDept
            from 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中使用左外部联接从“ objEmp1 ”,“ objDept1”集合中获取元素,并且在此我们指定了检查员工是否有部门的条件。如果未映射部门,则将从条件中获取“无部门”。

输出: