查询嵌套递归对象的性能问题

时间:2013-03-04 15:54:26

标签: c# performance linq-to-sql linq-to-entities

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

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

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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