Neilski
Neilski

Reputation: 4415

Listing deeply nested sub-entities in LINQ

I have a model that contains a number of nested collections. For example...

My Sales Record
  Contains a collection of Customers
    Each Customer contains a collection of Orders
      Each Order contains a collection of Items

I would like to be able to create a list of all the Items associated with the Sales Record without resulting to writing nested foreach loops. I have tried...

var items = SalesRecord.SelectMany(r => r.Customers)
               .SelectMany(c => c.Orders)
               .Select(o => o.Items);

but this doesn't work.

Is this achievable in LINQ?

Upvotes: 1

Views: 122

Answers (2)

Servy
Servy

Reputation: 203812

Use Select to map each sales record into an item that contains that record as well as a flattened list of items for that record, using several calls to SelectMany:

var items = SalesRecord.Select(record => new
{
    record,
    Items = record.Customers
        .SelectMany(c => c.Orders)
        .SelectMany(o => o.Items),
});

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

One more SelectMany needed:

var items = SalesRecord.Customers // simply select customers from record
               .SelectMany(c => c.Orders)
               .SelectMany(o => o.Items); // here

You need to flatten results, otherwise you will have collection of items collections. Also if you need a list of items, don't forget to call ToList() at the end of query.

Upvotes: 2

Related Questions