System.Data.DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(Int32));
dt.Columns.Add("name", typeof(string));
dt.Columns.Add("parentid", typeof(Int32));
dt.LoadDataRow(new object[] { 1, "a", 0 }, true);
dt.LoadDataRow(new object[] { 2, "b", 1 }, true);
dt.LoadDataRow(new object[] { 3, "c", 2 }, true);
dt.LoadDataRow(new object[] { 4, "6", 1 }, true);
dt.AsEnumerable().makeWebTreeView(
this.treeView1.Nodes,
p => Convert.ToInt32(p["id"]),
p => Convert.ToInt32(p["parentid"]),
p => new TreeNode() { Text = p["name"].ToString(), Tag = p },
p => p.Nodes);
static public class tools
{
public static void makeWebTreeView<TSource, TID, TNode>(
this IEnumerable<TSource> list,
IEnumerable tds,
Func<TSource, TID> FunID,
Func<TSource, TID> funParentID,
Func<TSource, TNode> funConvert,
Func<TNode, IEnumerable> ChirldFun,
decimal parentId = 0
) where TID : struct
{
var tlist = list.Where(c => Convert.ToDecimal(funParentID(c)) == parentId);
foreach (var item in tlist)
{
TNode td = funConvert(item);
dynamic d_tds = tds;
d_tds.Add(td);
list.makeWebTreeView(ChirldFun(td), FunID, funParentID, funConvert, ChirldFun,Convert.ToDecimal(FunID(item)));
}
}
}
扩展方法