110,534
社区成员
发帖
与我相关
我的任务
分享
public class Text
{
public Text Parent{get;set;}
public List<Text> Children{get;set;}
public Text()
{
this. Children=new List<Text>();
}
}
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>();
}
}