3 回答

TA貢獻1783條經驗 獲得超4個贊
這需要遞歸是一個誤解。這將需要一個堆?;蜿犃泻妥詈唵蔚姆椒ㄊ鞘褂眠f歸來實現它。為了完整起見,我將提供一個非遞歸答案。
static IEnumerable<Node> Descendants(this Node root)
{
var nodes = new Stack<Node>(new[] {root});
while (nodes.Any())
{
Node node = nodes.Pop();
yield return node;
foreach (var n in node.Children) nodes.Push(n);
}
}
例如,使用以下表達式來使用它:
root.Descendants().Where(node => node.Key == SomeSpecialKey)

TA貢獻1848條經驗 獲得超10個贊
如果您想要維護類似于Linq的語法,則可以使用一種方法來獲取所有后代(子代+孩子的子代等)。
static class NodeExtensions
{
public static IEnumerable<Node> Descendants(this Node node)
{
return node.Children.Concat(node.Children.SelectMany(n => n.Descendants()));
}
}
然后,可以像其他任何查詢一樣使用where或first或其他查詢該可枚舉的對象。

TA貢獻1785條經驗 獲得超8個贊
用Linq搜索對象樹
public static class TreeToEnumerableEx
{
public static IEnumerable<T> AsDepthFirstEnumerable<T>(this T head, Func<T, IEnumerable<T>> childrenFunc)
{
yield return head;
foreach (var node in childrenFunc(head))
{
foreach (var child in AsDepthFirstEnumerable(node, childrenFunc))
{
yield return child;
}
}
}
public static IEnumerable<T> AsBreadthFirstEnumerable<T>(this T head, Func<T, IEnumerable<T>> childrenFunc)
{
yield return head;
var last = head;
foreach (var node in AsBreadthFirstEnumerable(head, childrenFunc))
{
foreach (var child in childrenFunc(node))
{
yield return child;
last = child;
}
if (last.Equals(node)) yield break;
}
}
}
- 3 回答
- 0 關注
- 449 瀏覽
添加回答
舉報