TreeBuilder is a scientific tree builder.
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); }); } } }
Example:
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);
Parameter 1 is the data set of the component tree, parameter 2 is the tree node conversion delegate, parameter 3 is the root node selector, and parameter 4 is the parent-child relationship selector.