Search code examples
linqhierarchical

C# Find ultimate parent with LINQ


I have a hierarchical object with the following structure:

public class Folder
{
    public Folder Parent { get; set; }
    public IList<Folder> Child { get; set; }
}

If the folder is a root folder, the Parent will be null. If the folder is not a root the parent is not null.

I need to find the Ultimate parent of a Folder, that means, the root folder (not null) if exists one.

I would refer to avoid the while loop if possible. I would like to get it done using Linq expressions if possible.


Solution

  • Why avoid the while loop if it is the fastest way to do it?

    Folder root = myFolder;
    while(root.Parent != null) root = myFolder.Parent;