📜  使用 LINQ 加入查询加入员工和部门类的 C# 程序

📅  最后修改于: 2022-05-13 01:54:20.312000             🧑  作者: Mango

使用 LINQ 加入查询加入员工和部门类的 C# 程序

给定两个名为 Employee 和 Department 的类,现在我们在 LINQ join Query 的帮助下加入 Employee 和 Department 类。所以对于这个任务,我们使用 Join 子句。该子句用于将两个数据源连接成一个具有一些共同属性的源。它总是需要两个数据源,连接的结果取决于使用哪种类型的连接,如内连接、交叉连接、左外连接和组连接。

例子:

方法:

1.使用名为 Employee 的列表创建两个数据源,并通过声明变量创建 Department。

2.向这些列表添加值。

3.根据学生号和部门号进行加入。

var result = (from stu in employees
join dept in departments on stu.dept_id equals dept.dept_id).ToList();

4.使用 select() 方法选择数据。

select new
{
    ID = stu.id, Name = stu.name,
    DeptName = dept.dept_name,
}

5.使用每个循环显示输出。

foreach(var e in result)
{
    Console.WriteLine("ID: " + e.ID + 
                "--> Name: " + e.Name + 
          "--> Department: " + e.DeptName );
}

例子:

C#
// C# program to Join Employee and Department Class 
// using LINQ Join Query
using System;
using System.Linq;
using System.Collections.Generic;
  
// Variables for Employee list
public class Employee
{
    public int id;
    public string name;
    public int dept_id;
    public int add_id;
}
  
// Variables for Department list
public class Department
{
    public int dept_id;
    public string dept_name;
}
  
// Variables for Address list
public class Address
{
    public int add_id;
    public string address_name;
}
  
class GFG{
  
// Driver code
static void Main(string[] args)
{
      
    // Enter data for Employee list
    List employees = new List()
    {
        new Employee{ id = 234, name = "sravan kumar",
                      dept_id = 1},
        new Employee{ id = 244, name = "Monika",
                      dept_id = 2},
        new Employee{ id = 734, name = "harsha",
                      dept_id = 1},
        new Employee{ id = 533, name = "komal",
                      dept_id = 4},
    };
  
    List departments = new List()
    {
        new Department{ dept_id = 1, dept_name = "CSE" },
        new Department{ dept_id = 2, dept_name = "CSE" },
        new Department{ dept_id = 3, dept_name = "IT " },
    };
  
    // Join the employees  and other two tables
    var result = (from stu in employees
  
                join dept in departments on stu
                .dept_id equals dept
                .dept_id
  
                select new
                {
                    ID = stu.id, Name = stu.name,
                    DeptName = dept.dept_name,
                }).ToList();
                  
    // Display the result
    foreach(var e in result)
    {
        Console.WriteLine("ID: " + e.ID + 
                    "--> Name: " + e.Name + 
              "--> Department: " + e.DeptName );
    }
}
}


输出:

ID: 234--> Name: sravan kumar--> Department: CSE
ID: 244--> Name: Monika--> Department: CSE
ID: 734--> Name: harsha--> Department: CSE