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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With