首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 擴展方法進階技巧:通用樹狀結構遍歷擴展

     編輯:關於C語言

定義通用遞迴遍歷擴展 GetDescendants,支援任意樹狀結構:

單一型別樹(根與節點同型別)

public static IEnumerable<T> GetDescendants<T>(
    this T root,
    Func<T, IEnumerable<T>> childSelector,
    Predicate<T> filter) {
    foreach (var t in childSelector(root)) {
        if (filter == null || filter(t)) yield return t;
        foreach (var child in GetDescendants(t, childSelector, filter))
            yield return child;
    }
}

應用範例:People 家族樹

var allDescendants = people.GetDescendants(p => p.Children, null);
var maleDescendants = people.GetDescendants(p => p.Children, p => p.IsMale);

WinForms 控制項樹

var allControls = this.GetDescendants(c => c.Controls.Cast<Control>(), null);
var checkedBoxes = this.GetDescendants(
    c => c.Controls.Cast<Control>(),
    c => c is CheckBox && ((CheckBox)c).Checked).Cast<CheckBox>();

異型別樹(根與節點不同型別,如 TreeView/TreeNode)

public static IEnumerable<T> GetDescendants<TRoot, T>(
    this TRoot root,
    Func<TRoot, IEnumerable<T>> rootChildSelector,
    Func<T, IEnumerable<T>> childSelector,
    Predicate<T> filter) { ... }

TreeView 應用

var wineNodes = treeView1.GetDescendants(
    tv => tv.Nodes.Cast<TreeNode>(),
    tn => tn.Nodes.Cast<TreeNode>(),
    tn => tn.Text.EndsWith("酒"));

兩個多載涵蓋大多數樹遍歷需求,另可補充廣度優先版本。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved