TreeTemplate树模板
生活随笔
收集整理的這篇文章主要介紹了
TreeTemplate树模板
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
將創建樹形數據結構抽象出功能類
1 using System.Collections.Generic;2 using System;
3
4 public class TreeTemplate<T>
5 {
6 private readonly List<T> _data = new List<T>();
7
8 public TreeTemplate(List<T> items)
9 {
10 _data = items;
11 }
12 public List<Node<T>> GetTree(Func<T, bool> isRootPredicate, Func<T, T, bool> isChildPredicate)
13 {
14 var list = _data.FindAll(item => isRootPredicate(item));
15 var result = new List<Node<T>>();
16 list.ForEach(item => result.Add(GetTree(item, isChildPredicate)));
17 return result;
18 }
19 public Node<T> GetTree(T item, Func<T, T, bool> predicate)
20 {
21 var root = new Node<T> { Item = item };
22 InitializeNode(root, predicate);
23 return root;
24 }
26 private void InitializeNode(Node<T> node, Func<T, T, bool> isChildPredicate)
27 {
28 var lists = FindChild(node, isChildPredicate);
29 foreach (T item in lists)
30 {
31 var subNode = new Node<T> { Item = item };
32 node.Childs.Add(subNode);
33 InitializeNode(subNode, isChildPredicate);
34 }
35 }
36
37 private IEnumerable<T> FindChild(Node<T> node, Func<T, T, bool> isChildPredicate)
38 {
39 return _data.FindAll(item => isChildPredicate(node.Item, item));
40 }
41 }
使用TreeTemplate需要提供兩個判定函數原型為
public static bool IsRootPredicate(T item) -----判定Item是否為根節點
public static bool IsChildPredicate(T item1, T item2) ---- 判定item1是否為item2的父節點
//初始化一個List<T>,比如從數據庫里面抓取_data.Add(new Item { Id = 1, ParentId = 0, Name = "Item1", No="01"});
_data.Add(new Item { Id = 2, ParentId = 0, Name = "Item2", No="02"});
_data.Add(new Item { Id = 3, ParentId = 0, Name = "Item3", No="0101"});
_data.Add(new Item { Id = 11, ParentId = 1, Name = "Item11", No="0201"});
_data.Add(new Item { Id = 12, ParentId = 1, Name = "Item12", No="0202"});
_data.Add(new Item { Id = 121, ParentId = 12, Name = "Item121", No="020201"});
var tree = new TreeTemplate<Item>(_data);
//獲取樹形數據結構
List<Node<Item>> nodes =tree.GetTree(IsRoot, IsChild);
//判定是否為根節點
private static bool IsRoot(Item item)
{
return item.ParentId == 0;
}
//父子判定條件 - 根據Id及ParentId
private static bool IsChild(Item item1, Item item2)
{
return item1.Id == item2.ParentId;
}
源碼下載
轉載于:https://www.cnblogs.com/rroo/archive/2011/03/16/1986016.html
總結
以上是生活随笔為你收集整理的TreeTemplate树模板的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Item 添加事件 list grall
- 下一篇: Github客户端下载慢的解决方法