, Teudimundo . , . .
public class Thing
{
public IEnumerable<Thing> Children { get; set; }
public bool IsLeaf => Children == null || !Children.Any();
}
, , Thing. Children IsLeaf, , Thing . IEnumerable, .
public static class EnumerableExtensions
{
public static IEnumerable<TSource> Leaves<TSource>(this IEnumerable<TSource> source, Func<TSource, IEnumerable<TSource>> children, Func<TSource, bool> isLeaf)
{
var nodes = new Stack<TSource>(source);
while (nodes.Any())
{
var current = nodes.Pop();
if(isLeaf(current))
{
yield return current;
continue;
}
foreach (var child in children(current))
{
if (isLeaf(child))
{
yield return child;
}
else
{
nodes.Push(child);
}
}
}
}
}
, Linq. , Thing, , . .
var leaves = things.Leaves(t => t.Children, t => t.IsLeaf);
things IEnumerable of Thing. new List<Thing>() Thing things. Leaves - , . - Children, . IsLeaf, , , Thing . IEnumerable<Thing>, things. .ToList(), , . , !