3

我想知道从对象的嵌套层次结构中选择的最佳方法是什么?假设我们有一个类MyRecursiveObject如下:

 public class MyRecursiveObject
 {
   public Int64 Id { get; set; }
   public MyRecursiveObject Parent { get; set; }
 }

如何在选择 MyRecursiveObject 实例的所有父 ID 时达到最佳性能?

任何建议都受到高度赞赏。

4

2 回答 2

1

LinqToSql 不支持任意深度的行走树。您应该使用 TSQL While 循环编写一个 sql 函数来生成结果,并从 linqtosql 调用该 sql 函数。

就像是:

DECLARE @MyNodeID int
SET @MyNodeID = 42
  -- we're looking for the path from this ID back up to the root
  -- we don't know the length of the path.

DECLARE @MyTable TABLE
(
  int ID PRIMARY KEY,
  int ParentID,
)

DECLARE @ID int
DECLARE @ParentID int

SELECT @ID = ID, @ParentId = ParentId
FROM MyRecursiveObject
WHERE ID = @MyNodeID

WHILE @ID is not null
BEGIN

  INSERT INTO @MyTable (ID, ParentID) SELECT @ID, @ParentID

  SET @ID = null

  SELECT @ID = ID, @ParentId = ParentID
  FROM MyRecursiveObject
  WHERE ID = @ParentID

END

SELECT ID, ParentID FROM @MyTable  --results
于 2013-03-04T16:18:39.313 回答
1

您可以使用简单的循环而不是递归:

public IEnumerable<long> GetAllParentIdsOf(MyRecursiveObject obj)
{
    MyRecursiveObject child = obj;

   while (child.Parent != null)
   {
       child = child.Parent;
       yield return child.Id;
   }
}

样本:

MyRecursiveObject obj = new MyRecursiveObject {    
    Id = 1,
    Parent = new MyRecursiveObject {
        Id = 2,
        Parent = new MyRecursiveObject { Id = 3 }
    }
};

GetAllParentIdsOf(obj).ToList().ForEach(Console.WriteLine);

// 2
// 3
于 2013-03-04T15:59:05.170 回答