Tuesday, 10 September 2013

How to return a path of nodes from a recursive hierarchy given a condition?

How to return a path of nodes from a recursive hierarchy given a condition?

I'm trying to create a linq extension method that returns the path to a
selected node.
Path to node Item4 would yield - { Item1, Item2, Item4 }
Path to node Item3 would yield - { Item1, Item3 }
public class Item
{
public int Id { get; set; }
public IList<Item> Items { get; set; }
}
Item1
Item2
Item4
Item3
Calling Code
var path = myItem.Items
.Path(e => e.Items, e => MyPredicateCondition())
.ToList();
Extension Method
public static IEnumerable<T> Path<T>(
this IEnumerable<T> source,
Func<T, IEnumerable<T>> childrenSelector,
Predicate<T> condition)
{
if (source == null || !source.Any()) return default(T);
var attempt = source.FirstOrDefault(t => condition(t));
if (!Equals(attempt, default(T))) return attempt;
var items = source.SelectMany(childrenSelector)
.Path(childrenSelector, condition)
.ToList();
return attempt;
}
My problem is not finding the actual node, but returning nodes recursively
back up the tree to the root node. The data structure should stay how it
is - i.e. I don't want the Item referencing it's parent item.

No comments:

Post a Comment