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

标签 c# .net linq linq-to-sql

我有一张 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();

关于c# - LINQ:链 ID 从一行到另一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7290997/

相关文章:

c# - 依赖于 LinqToObjects 的自定义 IQueryProvider

c# - Enumerator 结构的可变性

c# - 如何使用 GDI+ 绘制圆环( donut )?

linq - RavenDB,LINQ,从字符串 [] 中选择,其中数组不包含给定的字符串

c# - 为什么当我乘以 double 时我得到零?

c# - XAML 中定义的 DataTemplate 具有 null VisualTree

c# - 遍历 LINQ 结果列表

c# - 从 XML 文件获取 ID 属性列表 C#

c# - 构造函数使用模拟对象,如何隔离测试方法?

.net - 您是否使用 TestInitialize 或测试类构造函数来准备每个测试?为什么?