C# 扁平化嵌套对象

3

我有一个嵌套的类:

    class Item
    {
        public Int32 Id { get; set; }
        public Int32 Pid { get; set; }
        public String Name { get; set; }
        public IEnumerable<Item> Children { get; set; }

    }

现在我想将其展开,以便获取所有项目及其子项的名称。

问题在于我不知道这个结构有多少层。

我查看了:

如何使用LINQ表达式展开嵌套对象

如果您知道有多少层,则此方法非常好用,但我不知道。

因此:

        var r = from b in items
                from c in b.Children
                from d in c.Children
                ...
                select new { b.Name, c = c.Name, d = d.Name ... };

这个程序基本上满足了我的需求,但我不知道需要多少级深度,如果一个项目没有子项,则不返回任何内容。

我想我需要一些递归例程,但我似乎找不到它。 我看了IEnumerable,但我还不太理解它 :)

因此,任何帮助都将非常感激。


很遗憾,Linq解决方案非常低效...我建议不要使用它(Eric Lippert也是这样建议的!) - Matthew Watson
1个回答

3
你说得对,需要使用递归:
public IEnumerable<Item> GetAllChildren(Item item)
{
    return item.Children.Concat(item.Children.SelectMany(GetAllChildren));
}

获取所有名称,您可以对结果进行投影:
var allDescendantNames = GetAllChildren(item).Select(child => child.Name).ToList();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接