无法获得我需要的正确查询结果

时间:2013-10-05 15:14:15

标签: c# recursion linq

我有一个对象

class item { Guid id; String name; List<item> childs;}

其数据有两部分。

咖啡馆

- 约翰

----盒

- 罗密欧

咖啡馆

- 约翰

- 罗密欧

----盒

所以,盒子刚改变了它的主人。

现在我需要将此结构作为String。

所以,必须是:

的咖啡厅,约翰,盒子,罗密欧

的咖啡厅,约翰,罗密欧,框

我有代码:

public static IEnumerable<item> get_in_one_row(this IEnumerable<item> itemsTree)
    {
        return itemsTree.Select(p=>p).Union(itemsTree.SelectMany(p=>p.childs.get_in_one_row()));
    }

但我总是得到:咖啡馆,约翰,罗密欧,盒子 - 无论如何,谁是盒子的主人。

我该怎么办?

感谢。

1 个答案:

答案 0 :(得分:1)

要按顺序获取结果,您需要以不同的方式遍历树:

public static IEnumerable<item> get_in_one_row(this IEnumerable<item> itemsTree)
    {
        return itemsTree.SelectMany(p => Enumerable.Repeat(p,1).Concat(p.childs.get_in_one_row()));
    }