LINQ内部联接

本文概述

  • LINQ内部联接的语法
  • LINQ内部联接示例
在LINQ中, 内部联接用于根据指定条件仅返回集合中匹配的记录或元素。
LINQ内部联接的语法 这是使用LINQ内部联接根据指定条件从集合中获取元素的语法。
var result = from d in objDeptjoin e in objEmpon d.DepId equals e.DeptIdselect new{EmployeeName = e.Name, DepartmentName = d.DepName};

从上述语法中, 我们试图基于匹配的” DeptId” 列值从” objEmp” , ” objDept” 集合中获取元素。
LINQ内部联接示例 这是使用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< Department> Dept = new List< Department> (){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 alist of the Employee with the added record*/List< Employee> Emp = new List< Employee> (){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 theemployee name and department namehere we mapped the employee with the department and store the result in the variable 'result'*/var result = from d in Deptjoin e in Empon d.DepId equals e.DeptIdselect new{EmployeeName = e.Name, DepartmentName = d.DepName}; //foreach loop traverse all the data in the result variable and store in item variableforeach (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 nameclass 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内部联接】从上面的示例中, 我们从两个集合(我们将雇员与部门映射)中获取了雇员名称和部门名称。

    推荐阅读