2
  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 表达式来选择部门位置为 Noida 的所有员工

4

2 回答 2

7

使用Any扩展方法:

var results = employees.Where(e => e.Department.Any(d => d.Location == "Noida"))
                       .ToList();
于 2013-08-12T08:46:49.590 回答
1

实际上,您甚至不需要 LINQ。List<T>有方法FindAllExsists可以完成这项工作:

employees.FindAll(e => e.Department.Exists(d => d.Location == "Noida"))
于 2013-08-12T09:03:50.993 回答