假設有一個資料表如下
| 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; } } } }
沒有留言:
張貼留言