📅  最后修改于: 2021-01-06 05:38:04             🧑  作者: Mango
在LINQ中,内部联接用于根据指定条件仅返回集合中匹配的记录或元素。
这是使用LINQ内部联接根据指定条件从集合中获取元素的语法。
var result = from d in objDept
join e in objEmp
on d.DepId equals e.DeptId
select new
{
EmployeeName = e.Name,
DepartmentName = d.DepName
};
从上述语法中,我们试图基于匹配的“ DeptId ”列值从“ objEmp ”,“ objDept”集合中获取元素。
这是使用LINQ内部联接根据指定条件从集合中获取元素的示例。
C#代码
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 of the department with the added record*/
List Dept = 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 'Employee' and create a
list of the Employee with the added record*/
ListEmp = new List
()
{
new Employee { EmpId=1,Name = "Akshay Tyagi", DeptId=1 },
new Employee { EmpId=2,Name = "Vaishali Tyagi", DeptId=1 },
new Employee { EmpId=3,Name = "Arpita Rai", DeptId=2 },
new Employee { EmpId=4,Name = "Sateesh Alavala", DeptId =2},
new Employee { EmpId=5,Name = "Madhav Sai"}
};
/*Linq query apply to fetch the information of the
employee name and department name
here we mapped the employee with the department and store the result in the variable 'result'*/
var result = from d in Dept
join e in Emp
on d.DepId equals e.DeptId
select new
{
EmployeeName = e.Name,
DepartmentName = d.DepName
};
//foreach loop traverse all the data in the result variable and store in item variable
foreach (var item in result)
{
/* Console.WriteLine(item.EmployeeName + "\t | " + item.DepartmentName)
will print the name of the employee and name of the department*/
Console.WriteLine(item.EmployeeName + "\t | " + item.DepartmentName);
}
Console.ReadLine();
}
}
//Create class 'Department' and 'Employee' and set the variable name
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; }
}
}
输出:
从上面的示例中,我们从我们将员工映射到部门的两个集合中获取了员工名称和部门名称。