简体   繁体   English

嵌套LINQ查询选择

[英]Nested LINQ query selection

Please consider following example class construct: 请考虑以下示例类构造:

public class Company
{
    public string CompanyName { get; set; }
    public List<Subdivision> Subdivisions { get; set; }
}
public class Subdivision
{
    public string SubdivisionName { get; set; }
    public List<Employee> Employees { get; set; }
}

public class Employee
{
    public int EmployeeID { get; set; }
    public string EmployeeName { get; set; }
}

Example variable of a List: 列表变量的示例:

List<Company> CompanyList = new List<Company>();
CompanyList.Add(new Company
    {
        CompanyName = "TestCompany",
        Subdivisions = new List<Subdivision>
        {
            { new Subdivision 
            {
               SubdivisionName = "TestSubdivision",
               Employees = new List<Employee>
                {
                    { new Employee
                        {
                            EmployeeID = 1,
                            EmployeeName = "John"
                        }
                    }
                }
            }}
        }
    });

I want to get the EmployeeName just by EmployeeID. 我想仅通过EmployeeID获取EmployeeName。 Consider this code: 考虑以下代码:

if (CompanyList.Any(x => x.Subdivisions.Any(y => y.Employees.Any(z => z.EmployeeID == 1))))
{
    int i1 = CompanyList.IndexOf(CompanyList.Where(x => x.Subdivisions.Any(y => y.Employees.Any(z => z.EmployeeID == 1))).Select(x => x).First());
    int i2 = CompanyList[i1].Subdivisions.IndexOf(CompanyList[i1].Subdivisions.Where(x => x.Employees.Any(z => z.EmployeeID == 1)).Select(x => x).First());
    int i3 = CompanyList[i1].Subdivisions[i2].Employees.IndexOf(CompanyList[i1].Subdivisions[i2].Employees.Where(z => z.EmployeeID == 1).Select(x => x).First());

    string i = CompanyList[i1].Subdivisions[i2].Employees[i3].EmployeeName;
    Console.WriteLine(i);                        
}
else
{
    Console.WriteLine("Employee with ID 1 not found!");
}

This works just fine; 这很好用; however, it seems rather bloated up if I just want to retrieve a piece of data without getting the indexes. 但是,如果我只想在不获取索引的情况下检索一条数据,那似乎就显得肿了。 Is there any other approach to this? 还有其他方法吗?

You can use SelectMany to search for all employees in all divisions in all companies and then use FirstOrDefault to make sure null would be returned if no employee would be found 您可以使用SelectMany在所有公司的所有部门中搜索所有员工,然后使用FirstOrDefault来确保如果找不到任何员工,则将返回null

var employee = CompanyList.SelectMany(company => company.Subdivisions.SelectMany(division => division.Employees))
                          .FirstOrDefault(emp => emp.EmployeeID == 1);
if (employee != null)
{
    Console.WriteLine(employee.EmployeeName); //prints John                  
}
else
{
    Console.WriteLine("Employee with ID 1 not found!");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM