📅  最后修改于: 2021-01-06 05:39:55             🧑  作者: Mango
在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交叉连接获取项目集合的笛卡尔积的示例。
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 objDept1 = new List(){
//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 objEmp1 = new List()
{
//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 objEmp1
from 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 Cross Join获得项集合的笛卡尔积的方式。