本文概述
- LINQ Cross Join的语法
- LINQ交叉连接示例
在LINQ Cross join中, 左侧集合上的每个元素都将映射到右侧集合上的所有元素。
LINQ Cross Join的语法 这是使用LINQ Cross连接获取集合项的笛卡尔积的语法。
var result = from e in objEmp1
from d in objDept1
select new
{
EmployeeName = e.Name, DepartmentName = d.DepName
};
根据上述语法, ” 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 the object of the Department List 'objDept1'
List<
Department>
objDept1 = new List<
Department>
(){
//assign the value in the Department
new Department{DepId=1, DepName="Software"}, new Department{DepId=2, DepName="Finance"}, new Department{DepId=3, DepName="Health"}
};
//Create the object of Employee List 'objEmp1'
List<
Employee>
objEmp1 = new List<
Employee>
(){
//Insert the value in the Employee list
new Employee { EmpId=1, Name = "Vaishali Tyagi", DeptId=1 }, new Employee { EmpId=2, Name = "Arpita Rai", DeptId=1 }, new Employee { EmpId=3, Name = "Vinay Tyagi", DeptId=2 }, new Employee { EmpId=4, Name = "Sateesh", DeptId =2}, new Employee { EmpId=5, Name = "Madhav"}};
/*apply the linq queries to fetch the value from the Employee
and Department list and store the value in variable 'result'*/
var result = from e in objEmp1from d in objDept1
//Select will fetch the name of the employee and name of the department
select new{EmployeeName = e.Name, DepartmentName = d.DepName};
//foreach loop will print the value of the result with the help of 'WriteLine' funtion
foreach (var item in result){Console.WriteLine(item.EmployeeName + "\t | " + item.DepartmentName);
}Console.ReadLine();
}}
//Here we create the class named Department and Employee and assignt the variable
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 Cross Join获得项目集合的笛卡尔积的方式。
推荐阅读
- LINQ Single()方法
- LINQ左外连接
- LINQ内部联接
- LINQ Join()运算符
- LINQ GroupBy()方法
- LINQ DefaultfEmpty()方法
- LINQ SingleOrDefault方法
- LINQ ElementAt()方法
- LINQ ElementAtOrDefault()方法