Linq or Sql 取树末级节点
电脑版发表于:2019/10/10 22:49
List<Entity> list = new List<Entity> { new Entity(){ Id = 1, Name="根",Pid = 0 }, new Entity(){ Id = 2, Name="木",Pid = 1 }, new Entity(){ Id = 3, Name="铁",Pid = 1 }, new Entity(){ Id = 4, Name="金",Pid = 1 }, new Entity(){ Id = 5, Name="木剑",Pid = 2 }, new Entity(){ Id = 6, Name="木棍",Pid = 2 }, new Entity(){ Id = 7, Name="铁棒",Pid = 3 }, new Entity(){ Id = 8, Name="铁枪",Pid = 3 } }; var l = from t in list let pp = (from p in list.Select(s => s.Pid) select p) where !pp.Contains(t.Id) select t;
sql:
SELECT * FROM tree where id not in( SELECT Pid from tree)
把所有的父级id找出来,然后id不在父级id的就是最后一级