Reputation: 65
i have the following classes:
class Outer
{
public ICollection<Inner> Inners
}
class Inner
{
public ICollection<Inner> Inners
}
I would like to order descending a list of outers by the total count of their Inners and nested Inners.
for example:
if i have 2 outers: the first has a collection of 3 inners, each with 1 nested inner then total is 5.
the second has for example can have a collection of 2 inners, each with 3 nested inner then the total count is 2 + 3 + 3 = 8
therefor in the returned result the second example should be the first.
Anyone? :)
Upvotes: 2
Views: 712
Reputation: 75316
First, build a recursive method to count the Inner objects inside a Inner
object including itself:
public static int Count(Inner inner)
{
var count = 1;
if (inner.Inners != null && inner.Inners.Any())
count += inner.Inners.Sum(x => Count(x));
return count;
}
Then you can order:
var result = outers.OrderBy(o => o.Inners.Sum(i => Count(i)));
Upvotes: 3