LINQ group连接

本文概述

在LINQ中, 带有’into’表达式的Join子句称为组联接。在LINQ中, 组联接产生对象元素的序列, 该序列基于左集合和右集合中的匹配元素。

如果没有从右集合与左集合中找到匹配的元素, 则join子句将返回一个空数组。在LINQ中, 组联接等效于内部等联接, 除了将元素组织成组的结果。

LINQ Group Join的语法

根据我们的要求, 使用LINQ Group Join从给定集合中获取匹配元素的语法。

var result = from d in objDept
join e in objEmp on d.DepId equals e.DeptId into empDept
select new
{
    DepartmentName = d.DepName, Employees = from emp2 in empDept
    orderby emp2.Name
     select emp2
};

根据上面的语法, 我们使用了带有” into”表达式的Join子句来从集合中获取匹配的元素。

LINQ group连接的例子

这是LINQ Group Join的示例, 可根据所需条件从集合中获取匹配的元素。

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 'objDept1' and add some values in the list of the 'Department'
            List<Department> objDept1 = new List<Department>
    (){
    //insert the data in the Department class
    new Department{DepId=1, DepName="Software"}, new Department{DepId=2, DepName="Finance"}, new Department{DepId=3, DepName="Health"}
    };
    //Create an object 'objEmp1' and add some values in the list of the 'Employee'
    List<Employee>objEmp1 = new List<Employee>()
            {
    //add the data in the Employee class
            new Employee { EmpId=1, Name = "Devansh", DeptId=1 }, new Employee { EmpId=2, Name = "Shubham", DeptId=1 }, new Employee { EmpId=3, Name = "Aman", DeptId=2 }, new Employee { EmpId=4, Name = "Raman", DeptId =2}, new Employee { EmpId=5, Name = "Madhav"}
            };
    //used the linq queries to group the elements of both the table by using the join clause based on the name of the department
            var result = from d in objDept1
            join e in objEmp1 on d.DepId equals e.DeptId into empDept
            select new
            {
            DepartmentName = d.DepName, Employees = from emp2 in empDept
            orderby emp2.Name
            select emp2
            };
            int totalItems = 0;
            foreach (var empGroup in result)
            {
            Console.WriteLine(empGroup.DepartmentName);
            foreach (var item in empGroup.Employees)
            {
            totalItems++;
            Console.WriteLine("    {0}", item.Name);
            }
            }
            Console.ReadLine();
            }
            }
    //create the class Department and Employee having the different information
            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; }
            }
            }

在上面的示例中, 我们将Join子句与’into’表达式一起使用, 并且根据部门名称对元素进行分组。

输出

LINQ group连接

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?