2017年11月17日 星期五

遞迴父子階層

遞迴除了在面試考題很常出之外,最常應用的應該就是在撈父子階層了
假設有一個資料表如下
| Id | Name    | ParentId |
|-------------------------|
| 1  | Ricky   | 2        |
| 2  | Jackie  | 3        |
| 3  | Peter   | 4        |
| 4  | Anson   | 5        |
| 5  | Austin  | 0        |

ParentID是主管的ID,所以這張表的意思就是

Ricky 的主管是 Jackie 
Jackie 的主管是 Peter 
Peter 的主管是 Anson 
Anson 的主管是 Austin 

這時候我想撈Ricky所有的上司,就可以使用遞迴
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {
        private static List _user = new List();            
        static void Main(string[] args)
        {
            _user.Add(new User { Id = 1, Name = "Ricky", ParentID = 2 });
            _user.Add(new User { Id = 2, Name = "Jackie", ParentID = 3 });
            _user.Add(new User { Id = 3, Name = "Peter", ParentID = 4 });
            _user.Add(new User { Id = 4, Name = "Anson", ParentID = 5 });
            _user.Add(new User { Id = 5, Name = "Austin", ParentID = 0 });            
            
            factorial(_user.Where(x=>x.Name=="Ricky").FirstOrDefault());//抓取Ricky上面所有的主管
            Console.ReadLine();
        }

        //遞迴抓取向上所有主管
        private static void factorial (User args)
        {
            var result = _user.Where(x => x.Id == args.ParentID).FirstOrDefault();
            if(result != null)
            {
                Console.WriteLine(string.Format("{0}的主管是{1}", args.Name, result.Name));
                factorial(result);
            }            
        }

        public class User
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int ParentID { get; set; }
        }
    }
}
結果如下

沒有留言:

張貼留言