Skip to main content
 首页 » 编程设计

c#之LINQ:链 ID 从一行到另一行

2024年02月23日12xiaohuochai

我有一张 table ,里面设置了一个 child -> child -> parent 。 (这是我在现有旧数据库上使用的补丁,所以有点不可靠)。

表的类:

public class Foo 
{ 
    int ID {get;set;} 
    int ParentID  {get;set;} 
    int BaseParentID {get;set;} 
} 

假设我在那里有一些记录

ID: 10, ParentID: 5, BaseParentID: 5 
ID: 05, ParentID: 1, BaseParentID: 5 
ID: 01, ParentID: 1, BaseParentID: 0 

我想做的是获取每个 ParentID,直到 baseparentid 为 0。所以在某种程度上,它是从一条记录到另一条记录遍历表并将其检索到 ID 列表中。

最终结果应该是一个列表:{ 10, 5, 1 }

这就是我现在正在做的(目前有 4 个的限制,但如果没有限制我会更喜欢它):

var list = new List<int?>(); 
var id = 10; // The first ID is given when this method is started. 
list.Add(id); 
int? pid = db.Foo.Where(w => w.ID == id).Single().BaseParentID; // i have this as a compiled query function 
if (pid != 0) { 
    list.Add(pid); 
    pid = db.Foo.Where(w => w.ID == pid).Single().BaseParentID; //  for the sake of this example i'm just using the query here 
    if (pid != null) { 
         list.Add(pid); 
         // And so on 
    } 
} 

如您所见,这样做有点糟糕。但我不确定是否有办法在花哨的 linq 查询中执行此操作。

附言。这一点是一种伪文件夹结构。

请您参考如下方法:

这是一个很好的例子,你可以在这里写一个单独的 iterator function :

 IEnumerable<Foo> TraverseParents(Foo foo, IEnumerable<Foo> all) 
 { 
      while(foo != null)  
      { 
          yield return foo; 
          foo = (foo.pid == 0) ? null : all.FirstOrDefault(f => f.ID == foo.pid); 
      } 
 } 
 
 // In the calling code 
 var id = 10; 
 Foo root = db.Foo.FirstOrDefault(f => f.ID == id); 
 List<int> list = TraverseParents(root, db.Foo) 
                   .Select(f => f.ID) 
                   .ToList();