简体   繁体   中英

How to traverse parent child data using Linq

I have a class with following structure:

public class OilCategory 
{
    public OilCategory Parent { get; set; } // For representing parent
    public string Name { get; set; }
    public int Position { get; set; }
    public int Id { get; set; }
}

And I have list collection of OilCategories:

OilCategory rootCategory = new OilCategory {Id = 1, Name = "Root", Position = 1, Parent = null};
OilCategory firstLevel1  = new OilCategory {Id = 2, Name = "fl-1", Position = 1, Parent = rootCategory};
OilCategory firstlevel2  = new OilCategory {Id = 3, Name = "fl-2", Position = 2, Parent = rootCategory};

OilCategory secondLeve1  = new OilCategory {Id = 4, Name = "sl-1", Position = 1, Parent = firstLevel1};
OilCategory secondlevel2 = new OilCategory {Id = 5, Name = "sl-2", Position = 2, Parent = firstLevel1};

List<OilCategory> categories=new List<OilCategory>();
;
categories.Add(rootCategory);
categories.Add(firstLevel1);
;categories.Add(firstlevel2);
categories.Add(secondLeve1);
categories.Add(secondlevel2);

From this collection categories (which has 5 categories with or without high level parent), how I can generate items like following structure {root/child/child/}:

Id            ItemName

1              root
2              root /fl-1
3              root /fl-2
4              root /fl-1/sl-1
5              root /fl-1/sl-1

Start out with a method to generate a sequence of the item, along with all of its ancestors:

public IEnumerable<OilCategory> Ancestors
{
    get
    {
        OilCategory current = this;
        while (current != null)
        {
            yield return current;
            current = current.Parent;
        }
    }
}

And then just reverse the sequences to get top down rather than bottom up ordering and join them together.

public string ItemName
{
    get
    {
        return string.Join("/",
            Ancestors.Reverse().Select(category => category.Name));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM