如何通过LINQ将树夷为平地?所以我有一棵简单的树:class MyNode{
public MyNode Parent;
public IEnumerable<MyNode> Elements;
int group = 1;}我有一个IEnumerable<MyNode>..我想要一份清单MyNode(包括内部节点对象(Elements)作为一个单一清单Where group == 1..如何通过LINQ做这样的事情?
3 回答
缥缈止盈
TA贡献2041条经验 获得超4个赞
IEnumerable<MyNode> Flatten(IEnumerable<MyNode> e) { return e.SelectMany(c => Flatten(c.Elements)).Concat(new[] {e});}
group
Where(...)
.
Flatten
public static IEnumerable<MyNode> Flatten(this IEnumerable<MyNode> e) { return e.SelectMany(c => c.Elements.Flatten()).Concat(e);}
Flatten
public static IEnumerable<T> Flatten<T>( this IEnumerable<T> e, Func<T,IEnumerable<T>> f) { return e.SelectMany(c => f(c).Flatten(f)).Concat(e);}
IEnumerable<MyNode> tree = ....var res = tree.Flatten(node => node.Elements);
Concat(...)
.
手掌心
TA贡献1942条经验 获得超3个赞
public static IEnumerable<T> Flatten<T>( this IEnumerable<T> items, Func<T, IEnumerable<T>> getChildren) { var stack = new Stack<T>(); foreach(var item in items) stack.Push(item); while(stack.Count > 0) { var current = stack.Pop(); yield return current; var children = getChildren(current); if (children == null) continue; foreach (var child in children) stack.Push(child); } }
- 3 回答
- 0 关注
- 414 浏览
添加回答
举报
0/150
提交
取消