jacobz
jacobz

Reputation: 3291

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. 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?

Upvotes: 0

Views: 95

Answers (1)

Ilya Ivanov
Ilya Ivanov

Reputation: 23646

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

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!");
}

Upvotes: 1

Related Questions