程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> TreeBuilder科學的樹創建器,treebuilder樹創建

TreeBuilder科學的樹創建器,treebuilder樹創建

編輯:C#入門知識

TreeBuilder科學的樹創建器,treebuilder樹創建


public static class TreeBuilder
    {
        public static List<dynamic> Build(IEnumerable<dynamic> collection, Func<dynamic, int, dynamic> parser, Func<dynamic, bool> rootSelector, Func<dynamic, dynamic, int, bool> childrenSelector)
        {
            if (collection != null && parser != null && rootSelector != null && childrenSelector != null)
            {
                var roots = collection.Where(rootSelector).Select(item => parser(item, 0)).ToList();
                roots.ForEach(node => { BuildChildren(collection, node, parser, 1, childrenSelector); });
                return roots;
            }
            return null;
        }

        private static void BuildChildren(IEnumerable<dynamic> collection, dynamic parent, Func<dynamic, int, dynamic> parser, int level, Func<dynamic, dynamic, int, bool> childrenSelector)
        {
            var children = collection.Where(t => childrenSelector(t, parent, level)).Select(item => parser(item, level)).ToList();
            if (children != null && children.Count > 0)
            {
                parent.state="closed";
                parent.children=children;
                children.ForEach(node => { BuildChildren(collection, node, parser, level + 1, childrenSelector); });
            }
        }
    }

示例:

string sql = @"SELECT  [Id]
      ,[PId]
      ,[Name]
      ,[OfficeTel]
      ,[Fax]
      ,[SafeTel]
      ,[MSTel]
      ,[ElectricTel]
      ,[Order]
      ,[Type]
  FROM [NEMS].[dbo].[ContactInfo] where [type]=@type order by [Order] ";
           BatchDataHelper helper = new BatchDataHelper("NEMSConnString");
           var list = helper.Query(sql, new List<KeyValuePair<string, object>>() { new KeyValuePair<string, object>("type", type) });
           var tree = TreeBuilder.Build(list, (d, i) =>
           {
               d.Level = i;
               
               return d;
           }, d => d.PId == 0, (d, n, i) => n.Id == d.PId);

參數一為構件樹的數據集合,參數二為樹節點轉化委托,參數三為根節點選擇器,參數四是父子關系選擇器.

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved