本文概述
- LINQ Group Join的语法
- LINQ group连接的例子
如果没有从右集合与左集合中找到匹配的元素, 则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连接】输出
文章图片
推荐阅读
- LINQ集合操作
- LINQ Single()方法
- LINQ交叉连接
- LINQ左外连接
- LINQ内部联接
- LINQ Join()运算符
- LINQ GroupBy()方法
- LINQ DefaultfEmpty()方法
- LINQ SingleOrDefault方法