programad
programad

Reputation: 1311

LINQ nested collection

I have a class that has a sub collection. Something like this:

public class Item { 
    public string Type {get;set}
    public Subitem[] {get;set;}
}

I know that I can separate and count by Type this way:

var count = (from x in items
            group x by x.Type into grouped
            select new {
                typename = grouped.Key,
                count = grouped.Count()
                }).ToDictionary<string, int>(x => x.typename, x => x.count);

This will return something like this:

{ type1, 13 } { type2, 26 }

and so on.

But how can I count by Subitem?

To return something like: { subitem1, 15 } { subitem2, 46 }

Upvotes: 0

Views: 1808

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160852

Your code sample is not legal C#, but suppose you have a collection called Subitems in your items - then you can use SelectMany() or in query syntax:

var count = (from i in items
             from x in i.Subitems
             group x by x into grouped
             select new 
             {
                typename = grouped.Key,
                count = grouped.Count()
              }).ToDictionary(x => x.typename, x => x.count);

Or alternatively in method syntax:

var countDict = items.SelectMany(x => x.Subitem)
                     .GroupBy(x => x)
                     .ToDictionary(g => g.Key, g => g.Count());

Upvotes: 2

Related Questions