linq aggregated nested count

风格不统一 提交于 2020-01-15 05:14:10

问题


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? :)


回答1:


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)));


来源:https://stackoverflow.com/questions/18041015/linq-aggregated-nested-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!