我知道以前也有人問過類似的問題,但我的一些關鍵差異會改變它。所以假設我在 C# 中有一個具有以下內容的類
public class Node
{
public string Type { get; set; }
public Node Parent { get; set; }
public List<Node> Children { get; set; }
}
而且我有某種樹結構,其型別類似于:
N1
- N1
- N1
N2
- N3
- N1
N3
N4
- N5
- N1
-N6
N1
N1
- N2
如何按型別過濾:N1所以上面的樹看起來像這樣:
N1
- N1
- N1
N2
- N1
N4
- N5
- N1
N1
N1
基本上我想按 Type: 過濾,N1但如果某個子節點有 Type: 則離開父節點N1。我正在尋找可以實作此目的的簡單 C# 方法,我不想添加任何庫或任何東西。就像是:
tree = FilterTree(type, ...)
uj5u.com熱心網友回復:
這是使用遞回和Func<Node, bool>委托的建議。
如果你有一個List<Node> tree,你可以實作相互呼叫的擴展方法:
public static IEnumerable<Node> BuildTreeWithLeafNodes(
this IEnumerable<Node> topNodes,
Func<Node, bool> leafNodeCondition)
{
return topNodes
.Select(topNode => topNode.GetSubTreeWithLeafNodes(leafNodeCondition))
.Where(subTree => subTree != null);
}
public static Node GetSubTreeWithLeafNodes(
this Node node,
Func<Node, bool> leafNodeCondition)
{
if (node.Children != null && node.Children.Any())
{
node.Children = node.Children
.BuildTreeWithLeafNodes(leafNodeCondition)
.ToList();
if (node.Children != null && node.Children.Any())
{
return node;
}
}
return leafNodeCondition(node) ? node : null;
}
并通過呼叫獲取過濾樹:
var filteredTree = tree.BuildTreeWithLeafNodes(node => node.Type == "N1");
示例小提琴在這里。
發生了什么?
BuildTreeWithLeafNodes()接受Nodes 的集合并回傳 s 的集合,Node其中以下選擇條件適用于原始集合中的每個節點:
- 如果節點最初是無子節點或沒有后代滿足
leafNodeCondition,則僅當節點本身滿足時,節點(沒有子節點)才會包含在回傳集合中。leafNodeCondition - 如果該節點最初有孩子并且至少有一個后代滿足
leafNodeCondition,則調整該節點的子樹(node.Children及其后代),使其僅包含每個分支的葉節點滿足的分支leafNodeCondition,以及具有調整子的節點樹包含在回傳集合中。
The whole process can be visualized as a "descendant trimming" that is working itself up from each original leaf node and towards the top nodes (the original collection).
Basically, the way BuildTreeWithLeafNodes() and GetSubTreeWithLeafNodes() are calling each other, each original Node's sub trees (Children and their descendants) are being traversed all the way down to each respective sub tree's leaf node. If the leaf node does not satisfy the leafNodeCondition, it is removed from the parent node's Children. Once a parent node loses all its children (i.e. if none of the children satisfy the leafNodeCondition), the parent node itself will be removed from its own parent's Children unless it satisfies the leafNodeCondition.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/435230.html
