[英]LINQ select items from a list within a list
Assuming I have classes defined as below 假设我有如下定义的类
public class Employee
{
public string Name { get; set;}
public string Type { get; set; }
}
public class Dept
{
public string Name { get; set;}
public string Category { get; set; }
public List<Employee> Employees { get; set;}
}
public class NewModel
{
public string Category { get; set;}
public List<string> EmpNames { get; set;}
}
How do I select all the elements into a new model which Employee type is A and group by Category? 如何将所有元素选择到Employee类型为A并按类别分组的新模型中?
The new model should have Category (from Dept which is grouped key) and list of Employee Names. 新模型应具有类别(来自部门的分组键)和雇员姓名列表。 I have done the below but it doesn't give me what I want.
我已经完成了下面的工作,但并没有给我我想要的东西。
var result = Dept.Where(p =>p.Employees != null && p.Employees.Any(x => x.Type == 'A')).GroupBy(g => g.Category, (key,g) => new NewModel { Category = key, EmpNames = g.Select(p => p.Name).ToList()});
Any hints? 有什么提示吗?
var departments = new List<Dept>(); // ? fill
var result =
departments.GroupBy(d => d.Category)
.Select(g => new NewModel
{
Category = g.Key,
EmpNames = g.SelectMany(d => d.Employees)
.Where(e => e.Type == "A")
.Select(e => e.Name)
});
This should give you expected result:- 这应该给您预期的结果:
var result = depts.SelectMany(x => x.Employees.Where(z => z.Type == "A")
, (DeptObj, empObj) =>
new
{
DeptObj.Category,
empObj
}
).GroupBy(x => x.Category)
.Select(x =>
new NewModel
{
Category = x.Key,
EmpNames = x.Select(z => z.empObj.Name).ToList()
});
As per your question description, there should not be single object of Dept
, instead you will (need to) have List of dept object. 根据您的问题描述,不应有
Dept
单个对象,而是您将(需要)具有dept对象的List。
adding working code below, 在下面添加工作代码,
List<Dept> deptList = new List<Dept>();
List<Employee> empList = new List<Employee>();
empList.Add(new Employee("d1" + "e1", "A"));
empList.Add(new Employee("d1" + "e2", "B"));
empList.Add(new Employee("d1" + "e3", "A"));
deptList.Add(new Dept("D1", "D1C1", empList));
empList = new List<Employee>();
empList.Add(new Employee("d2" + "e1", "A"));
empList.Add(new Employee("d2" + "e2", "B"));
empList.Add(new Employee("d2" + "e3", "A"));
deptList.Add(new Dept("D2", "D2C2", empList));
empList = new List<Employee>();
empList.Add(new Employee("d3" + "e1", "A"));
empList.Add(new Employee("d3" + "e2", "B"));
empList.Add(new Employee("d3" + "e3", "A"));
deptList.Add(new Dept("D3", "D1C1", empList));
List<NewModel> result = deptList
.Where(p => p.Employees != null &&
p.Employees
.Any(x => x.Type == "A")) //here this line is no more then just a check and can ignored
.GroupBy(g => g.Category,
(key, g) => new NewModel
{
Category = key,
EmpNames = g.SelectMany(p => p.Employees.Where( x => x.Type == "A").Select(x => x.Name)).ToList()
}).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.