LINQ 表示列表列表
本文关键字:列表 表示 LINQ | 更新日期: 2023-09-27 18:27:28
public class Employee
{
public string Name{get;set;}
public List<Department> Department { get; set; }
public string Company{get;set;}
}
public class Department
{
public string Name { get; set; }
public string Location { get; set; }
}
List<Employee> employees = new List<Employee>();
employees.Add(new Employee() { Company = "Dell", Name = "ABC" });
employees.Add(new Employee() { Company = "Dell", Name = "Aakash" });
employees.Add(new Employee() { Company = "CSC", Name = "Vaibhav" });
employees.Add(new Employee() { Company = "TCS", Name = "Sambhav" });
employees[0].Department = new List<Department>();
employees[0].Department.Add(new Department() { Location = "Delhi", Name = "HR" });
employees[0].Department.Add(new Department() { Location = "Delhi", Name = "Recruitment" });
employees[1].Department = new List<Department>();
employees[1].Department.Add(new Department() { Location = "Noida", Name = "EAO" });
employees[1].Department.Add(new Department() { Location = "Delhi", Name = "Arch" });
employees[2].Department = new List<Department>();
employees[2].Department.Add(new Department() { Location = "Denmark", Name = "Scandi" });
employees[2].Department.Add(new Department() { Location = "Noida", Name = "SAG" });
employees[3].Department = new List<Department>();
employees[3].Department.Add(new Department() { Location = "Mumbai", Name = "NSE" });
我需要编写一个 lambda 表达式来选择部门位置为诺伊达的所有员工
使用Any
扩展方法:
var results = employees.Where(e => e.Department.Any(d => d.Location == "Noida"))
.ToList();
实际上,您甚至不需要 LINQ 来实现这一点。 List<T>
有方法FindAll和Exsists可以完成这项工作:
employees.FindAll(e => e.Department.Exists(d => d.Location == "Noida"))