Reputation: 1013
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
Upvotes: 1
Views: 1069
Reputation: 203848
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));
}
}
Upvotes: 5