1

I have a query, which has one to many relation with LegalEntity table, my goal is to get a List of all LegalEntityIds. At this point I have following select which produces List<IEnumerable<string>>, is there a quick and efficient way without looping and creating separate list to flatten the inner lists into one.

var legalEntityIds = query.Select(x => x.LegalEntities.Select(y => y.LegalEntityId)).ToList();
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Working Pickle
  • 122
  • 3
  • 10

1 Answers1

7

Use SelectMany:

var legalEntityIds = 
    query.SelectMany(x => x.LegalEntities).Select(y => y.LegalEntityId).ToList();

or, using query syntax:

var legalEntityIds = (
    from item in query
    from legalEntity in item
    select legalEntity.LegalEntityId
).ToList();
jeroenh
  • 26,362
  • 10
  • 73
  • 104