求一个数据源为datatable从而构建一个树状结构的算法

.Net技术 码拜 8年前 (2016-09-17) 912次浏览
如题所示,datatable中有两列(id,pid),假如有条数据的id等于另一条数据的pid,那么他俩就有父子关系了。数据大致两百条,有多少层未知,现有个类

public class Text
{
public Text Parent{get;set;}
public List<Text> Children{get;set;}
public Text()
{
this. Children=new List<Text>();
}
}

希望是存放在一个List<Text>里面
现在本人用递归,发觉复杂度有点高。

解决方案

40

        static void Main(string[] args)
        {
            //构造一个 DataTable
            var dt = new DataTable();
            dt.Columns.Add(new DataColumn("id", typeof(int)));
            dt.Columns.Add(new DataColumn("pid", typeof(int)));
            dt.Rows.Add(1, 0);
            dt.Rows.Add(2, 0);
            dt.Rows.Add(3, 1);
            dt.Rows.Add(4, 2);
            dt.Rows.Add(5, 3);
            //从 DataTable 生成 List<Text>
            var res = (from x in dt.AsEnumerable() select new Text((int)x["id"], (int)x["pid"])).ToList();
            //匹配父子关系
            foreach (var x in res) x.Children = res.FindAll(n => n.Pid == x.Id);
            //打印一下
            foreach (var x in res) see(x);
            Console.ReadKey();
        }
        //生成不需要递归,访问却是要递归的
        static void see(Text a, int n=0)
        {
            Console.WriteLine("{0,"+n+"}id:{1} pid:{2}", "", a.Id, a.Pid);
            foreach (var x in a.Children) see(x, n + 4);
        }
        public class Text
        {
            public Text Parent { get; set; }
            public List<Text> Children { get; set; }
            public int Id = 0;
            public int Pid = 0;
            public Text(int id, int pid)
            {
                Id = id;
                Pid = pid;
                this.Children = new List<Text>();
            }
        }

求一个数据源为datatable从而构建一个树状结构的算法


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明求一个数据源为datatable从而构建一个树状结构的算法
喜欢 (0)
[1034331897@qq.com]
分享 (0)