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 }
Your code sample is not legal C#, but suppose you have a collection called
Subitemsin your items – then you can useSelectMany()or in query syntax:Or alternatively in method syntax: