使用LINQ LAMBDA让员工进入每个部门 [英] Getting employees in each dept using LINQ LAMBDA

查看:85
本文介绍了使用LINQ LAMBDA让员工进入每个部门的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用LINQ将两个表的员工和部门合并在一起,并尝试以下面的图像格式获取结果.有人可以帮忙实现这一目标.

I am trying to join two tables employee and department using LINQ and trying to get results in given below image format. Can some one help how to achieve this.

如何使每个部门的员工都参与进来.

how to achieve employees present in each department.

这是我的代码

var EmpList = (from d in Department
 join e in Employee on d.ID equals e.ID
 select new
 {
   ID = d.ID, Name = d.Name, Location = d.location,  Employess =  
   e.FirstName, e.LastName, e.Gender
 });

以上代码未完全编写.我对如何实现这一目标一无所知.

The above code not fully written. I am not getting any ideas how to achieve this.

var elist = from d in db.Departments
                    join e in db.Employees on d.ID equals e.ID
                    group d by e.DepartmentId into g
                    select new { Details = g };

推荐答案

假定您具有这样的结构:

Assuming that you have a structure like this:

var depts = new[] {
    new Dept { ID = 1, Name = "IT", Location = "New York" },
    new Dept { ID = 2, Name = "HR", Location = "London" },
    new Dept { ID = 3, Name = "Payroll", Location = "Sydney" }
};

var employees = new[] {
    new Employee { ID = 1, FirstName = "Mark", DeptID = 1 },
    new Employee { ID = 2, FirstName = "Steve", DeptID = 3 },
    new Employee { ID = 3, FirstName = "Ben", DeptID = 1 },
    new Employee { ID = 4, FirstName = "Philip", DeptID = 2 },
    new Employee { ID = 5, FirstName = "Mary", DeptID = 2 },
    new Employee { ID = 6, FirstName = "Valarie", DeptID = 3 },
    new Employee { ID = 7, FirstName = "John", DeptID = 1 }
};

您可以使用LINQ Join和GroupBy来获取所需的数据:

You can use LINQ Join and GroupBy to get the desired data:

var result = depts
    .Join(employees.GroupBy(x => x.DeptID), dept => dept.ID, empGroup => empGroup.Key,
        (dept, empGroup) => new { 
            Name = dept.Name, 
            Location = dept.Location, 
            Employees = empGroup.ToArray() 
        });

或类似SQL的语法:

var result = from dept in depts
             join empGroup in (
                from e in employees
                group e by e.DeptID into g
                select g
             ) on dept.ID equals empGroup.Key
             select new { 
                Name = dept.Name, 
                Location = dept.Location, 
                Employees = empGroup.ToArray()
             };

这实际上是做什么的?

  1. 员工按DeptID分组.
  2. 部门通过此分组合并,并生成所需格式的匿名对象的集合.当然,您可以使用强类型的类.
  1. Employees are grouped by DeptID.
  2. Departments are joined with this grouping and result into a collection of anonymous objects of desired format. Of course, you can use a strongly-typed class.

这篇关于使用LINQ LAMBDA让员工进入每个部门的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆