Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance issue on query over nested recursive objects

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.

like image 679
M.Mohammadi Avatar asked Mar 22 '26 03:03

M.Mohammadi


1 Answers

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
like image 74
Sergey Berezovskiy Avatar answered Mar 23 '26 17:03

Sergey Berezovskiy