根据此数据:
var item1 = new Item(1);
var item2 = new Item(2);
var item3 = new Item(3);
var item4 = new Item(4);
var item5 = new Item(5);
var item6 = new Item(6);
var item7 = new Item(7);
var item8 = new Item(8);
item1.Requirements = new List<Item>() { item2, item3 };
item2.Requirements = new List<Item>() { item4, item5 };
item5.Requirements = new List<Item>() { item6 };
item6.Requirements = new List<Item>() { item8 };
我想让所有item1
个孩子和所有孩子的孩子。
var items = item1.Requirements.SelectManyRecursive(x => x.Requirements).ToList();
我管理了这段代码:
public static IEnumerable<T> SelectManyRecursive<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector)
{
var result = source.SelectMany(selector);
if (!result.Any())
{
return result;
}
return result.Concat(result.SelectManyRecursive(selector));
}
我期望的结果是
item2, item3, item4, item5, item6, item8
很不幸,它缺少item2
和item3
。我可以通过以下方法解决此问题:
var items = item1.Requirements.Concat(item1.Requirements.SelectManyRecursive(x => x.Requirements)).ToList();
但这看起来很丑。还有其他方法吗?
答案 0 :(得分:0)
一种方法是使用扩展方法:
public static IEnumerable<T> SelectChildren<T>(this T RootNode, Func<T, IEnumerable<T>> childSelector)
{
var firstLevelChildren = childSelector(RootNode);
return firstLevelChildren.Concat(firstLevelChildren.SelectMany(c => SelectChildren(c, childSelector)));
}
var items = item1.SelectChildren(x => x.Requirements);
foreach (var item in items)
{
Console.WriteLine(item);
}