当前位置: 代码迷 >> C# >> 遍历LIST,该如何解决
  详细解决方案

遍历LIST,该如何解决

热度:34   发布时间:2016-05-05 03:22:56.0
遍历LIST
List<model>,model:属性为 Father 父节点,Child 子节点,Deep 节点所在深度.
因为数据量不小,本人写的又渣,经常卡很久.有没有大神帮帮忙的.
比如List里有
M0,Father:null,Child:M1,Deep:1;
M0,Father:null,Child:M2,Deep:1;
M0,Father:null,Child:M3,Deep:1;
M0,Father:null,Child:M4,Deep:1;
M2:Father:M0,Child:M5,Deep:2;
M4:Father:M0,Child:M6,Deep2;
M6:Father:M4,Child:M7,Deep:3;
输出的结果是 M0,M1,M2,M5,M3,M4,M6,M7
------解决思路----------------------
这不是一个标准的树在数据库里的存储方式吗?
------解决思路----------------------
找下递归遍历就可以了,下面的是例子
static void TreeABCEDFA()
        {
            List<RecursionTestDemo> list = new List<RecursionTestDemo>();
            list.Add(new RecursionTestDemo()
            {
                ID = 1,
                PID = 0
            });
            list.Add(new RecursionTestDemo()
            {
                ID = 2,
                PID = 0
            });
            list.Add(new RecursionTestDemo()
            {
                ID = 3,
                PID = 0
            });
            list.Add(new RecursionTestDemo()
            {
                ID = 4,
                PID = 1
            });
            list.Add(new RecursionTestDemo()
            {
                ID = 5,
                PID = 4
            });
            list.Add(new RecursionTestDemo()
            {
                ID = 6,
                PID = 3
            });
            ConsoleWriteTreeID(list, 0);
        }
        static void ConsoleWriteTreeID(IEnumerable<RecursionTestDemo> list, int pid)
        {
            var tmp = list.Where(x => x.PID == pid);
            foreach (var m in tmp)
            {
                Console.WriteLine("TreeID:" + m.ID+" TreeParentID:"+m.PID)  ;
                ConsoleWriteTreeID(list, m.ID);
            }
        }


class RecursionTestDemo
    {
        public int ID { get; set; }
        public int PID { get; set; }
        public string Name { get; set; }

        public override string ToString()
        {
            return string.Format("ID:{0} PID:{1} Name:{2}", this.ID, this.PID, this.Name);
        }
    }
  相关解决方案