定義通用遞迴遍歷擴展 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;
}
}
var allDescendants = people.GetDescendants(p => p.Children, null);
var maleDescendants = people.GetDescendants(p => p.Children, p => p.IsMale);
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>();
public static IEnumerable<T> GetDescendants<TRoot, T>(
this TRoot root,
Func<TRoot, IEnumerable<T>> rootChildSelector,
Func<T, IEnumerable<T>> childSelector,
Predicate<T> filter) { ... }
var wineNodes = treeView1.GetDescendants(
tv => tv.Nodes.Cast<TreeNode>(),
tn => tn.Nodes.Cast<TreeNode>(),
tn => tn.Text.EndsWith("酒"));
兩個多載涵蓋大多數樹遍歷需求,另可補充廣度優先版本。