Been trying to solve this without progress for a couple days, my question:
Given an entity in a hierarchy, return
a list of the immediate-ascendants (or
parents) of the entity.
When I want to know the hierarchy of “Entity 1.2.2.2” it would return a list containing only the bold items:
Entity 1
- Entity 1.1
- Entity 1.2
- Entity 1.2.1
- Entity 1.2.2
- Entity 1.2.2.1
- Entity 1.2.2.2
- Entity 1.2.3
- Entity 1.2.4
- Entity 1.2.4.1
- Entity 1.3
- Entity 1.4
Entity 2
...
Hence, expected result:
Entity 1
- Entity 1.2
- Entity 1.2.2
- Entity 1.2.2.2
Implementation code:
class Entity
{
public Entity Parent { get; set; }
public bool AbsoluteParent
{
get
{
return Parent == null;
}
}
public IEnumerable<Entity> Hierarchy //problem
{
get
{
return AbsoluteParent
? new [] { this }
: new [] { this }.Concat( Parent.Hierarchy );
}
}
}
The array attempt above is just one of the options I have been trying, that code actually returns something like:
Entity 1
Entity 1
- Entity 1.2
Entity 1
- Entity 1.2
- Entity 1.2.2
Entity 1
- Entity 1.2
- Entity 1.2.2
- Entity 1.2.2.2
I am able to achieve the expected results using jQuery’s parents() function, I’ve been reading the yield return keywords but still stuck in its more (I guess) functional style which I’m still baby-stepping into.
Not a very LINQ way of doing it (my LINQ is still pretty new):