问题描述
我有以下课程:
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.
例如:
如果我有2个外部元素:第一个具有3个内部元素的集合,每个内部元素带有1个嵌套内部元素,则总数为5.
if i have 2 outers: the first has a collection of 3 inners, each with 1 nested inner then total is 5.
第二个具有例如2个内部的集合,每个内部有3个嵌套内部,然后总计数为2 + 3 + 3 = 8
the second has for example can have a collection of 2 inners, each with 3 nested inner thenthe total count is 2 + 3 + 3 = 8
因此,在返回的结果中,第二个示例应该是第一个示例.
therefor in the returned result the second example should be the first.
有人吗? :)
推荐答案
首先,构建一个递归方法以对Inner
对象(包括其自身)中的内部对象进行计数:
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;
}
然后您可以订购:
var result = outers.OrderBy(o => o.Inners.Sum(i => Count(i)));
这篇关于linq聚合嵌套计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!