在LINQ查询

时间:2016-01-28 23:01:51

标签: c# linq

我有一个部门列表。每个部门都有一份员工清单。我需要退回2015年1月15日之后被雇用的所有员工。但我需要返回一份名单&#34; Roster&#34;即List<Roster>。我需要LINQ查询的帮助。

这是我的部门课程

public class Department
{
   public int DepartmentId { get; set; }
   public string DepartmentName { get; set; }
   public List<Employee> Employees { get; set; } = new List<Employee>();
   public string Location { get; set; }
}

我的员工班看起来像这样:

public class Employee
{
   public int EmployeeId { get; set; }
   public Guid PersonId { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string Gender { get; set; }
   public DateTime DateOfBirth { get; set; }
   public DateTime HireDate { get; set; }
}

这是我的名册课程

public class Roster
{
   public int DepartmentId { get; set; }
   public string DepartmentName { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string Gender { get; set; }
   public DateTime HireDate { get; set; }
}

这是我的查询到目前为止的样子:

var employees = departments.Where(x => x.Employees).Any(o => o.HireDate >= Convert.ToDateTime("1/15/2015")).Select(i => new Roster { ??? }).ToList();

请记住,我想返回List<Roster>,并且需要在结果中包含部门和员工信息。我不确定如何从Department对象获取一些数据,而从Employee获取一些数据来创建Roster类。感谢。

3 个答案:

答案 0 :(得分:7)

var rosters = departments.SelectMany(
    x => x.Employees
      .Where(y => y.HireDate >= Convert.ToDateTime("1/15/2015"))
      .Select(y => new Roster{ DepartmentId = x.DepartmentId, DepartmentName = x.DepartmentName, FirstName = y.FirstName, LastName = y.LastName, Gender = y.Gender, HireDate = y.HireDate})
  ).ToList();

受欢迎的需求 - 解释:

departments.SelectMany(x => x.Employees…) - 加入单个员工名单中所有部门的员工。

.Where(…) - 仅过滤在特定日期之后被雇用的员工

.Select(y => new Roster{…}) - 为每个选定的员工创建Roster个对象。此时,我们可以访问两个lambda变量(x - 代表部门,y - employee),并可以使用它们来填充Roster个对象字段。

警告: 如果员工被分配到多个部门,则会给予重复。

答案 1 :(得分:1)

像这样的一般想法,但它应该被重构

        var departments = new List<Department>();
        var employees = new List<Employee>();

        var result = employees
                        .Where(e => e.HireDate >= Convert.ToDateTime("1/15/2015"))
                        .Select(e => new Roster
                        {
                            FirstName = e.FirstName,
                            LastName = e.LastName,
                            Gender = e.Gender,
                            HireDate = e.HireDate,
                            DepartmentId = departments.First(d => d.Employees.Any(ee => e.EmployeeId == e.EmployeeId)).DepartmentId,
                            DepartmentName = departments.First(d => d.Employees.Any(ee => e.EmployeeId == e.EmployeeId)).DepartmentName
                        });

答案 2 :(得分:0)

var rosters = employees.Where(e => e.HireDate > someDate)
               .Select(s => new Roster {
                     LastName = s.FirstName,
                     Dept = s.Department.DepartmentName

注意 - 为此,您需要将department属性添加到员工对象中。

或在员工和部门之间进行联接