3

I'm wondering what is the best way to select from a nested hierarchy of objects? Assume that we a class MyRecursiveObject as below:

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

How can I reach to maximum performance while selecting all parent Ids of an instance of MyRecursiveObject?

Any suggestion is highly appreciated.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
M.Mohammadi
  • 1,558
  • 1
  • 13
  • 25

2 Answers2

1

You can use simple loop instead of recursion:

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

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

Sample:

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

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

// 2
// 3
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
1

LinqToSql doesn't support walking trees of arbitrary depth. You should write a sql function with a TSQL While loop to generate the results, and call that sql function from linqtosql.

Something like:

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
Amy B
  • 108,202
  • 21
  • 135
  • 185