Guerrilla Guerrilla - 1 year ago 79
C# Question

Getting list of child entity nested several levels with LINQ

I have entities that are nested in this order:


When given a RootDomain I want to create a list of all CompanyOfficers that have an email address but I am not sure how to do this.

Here Is my non-working attempt:

RootDomain rd = db.RootDomains.Find(123);
List<CompanyOfficer> col = rd.Companies.Where(x => x.CompaniesHouseRecords.Any(chr => chr.CompanyOfficers.Any(co => co.Email != null)))
.Select(x => x.CompaniesHouseRecords.Select(chr => chr.CompanyOfficers)).ToList();

I am obviously way off the mark here. Can someone show me or point me to the correct method for dong this?

Answer Source

Like this:

RootDomain rd = db.RootDomains.Find(123);
List<CompanyOfficer> col = rd.Companies
  .SelectMany(c => c.CompaniesHouseRecords)
  .SelectMany(c => c.CompanyOfficers)
  .Where(o => null != o.Email).ToList();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download