日期:2014-05-20  浏览次数:20747 次

问个递归算法
id pid remark
1 0 A

2 0 A

3 1 B
 
4 1 B

5 3 C 

6 3 C

7 4 D 
 
8 2 D

如果有个LIST存放了8行上面的数据,第一列是父信息,第二列是子信息,0则是顶层,remark是额外判断条件,

比如 1 0 下面所有子信息有 3 1,4 1,5 3,6 3,7 4;1 0下面所有remark为C的则有 5 3,6 3,我想问的是如何通过递归算法得出1 0 的子信息?最好是用linq to object



------解决方案--------------------
C# code

public class recursionList
    {
        public recursionList(int id,int pid,string remark)
        {
            this.id = id;
            this.pid = pid;
            this.remark = remark;
        }
        public int id { get; set; }
        public int pid { get; set; }
        public string remark { get; set; }
    }

 public static List<recursionList> GetAllChirlds(List<recursionList> source,int id)
        {
           List<recursionList> result = new List<recursionList>();
           recursionList parentM=source.FirstOrDefault(e => e.id == id);
           List<recursionList> chirldMs = source.Where(e => e.pid == parentM.id).ToList();
           if (chirldMs.Count > 0)
           {
               result.AddRange(chirldMs);
               foreach (var item in chirldMs)
               {
                   List<recursionList> subsubs = GetAllChirlds(source, item.id);
                   if (subsubs.Count > 0)
                       result.AddRange(subsubs);
               }
           }
           return result;
        }

public static void Main(string[] args)
        {
            List<recursionList> templist = new List<recursionList>() { 
            new recursionList(1,0,"A"),
            new recursionList(2,0,"A"),
            new recursionList(3,1,"B"),
            new recursionList(4,1,"B"),
            new recursionList(5,3,"C"),
            new recursionList(6,3,"C"),
            new recursionList(7,4,"D"),
            new recursionList(8,2,"D"),
            };

            var allsubs = GetAllChirlds(templist, 1);
      }