I have a hierarchy of of groups, and I want to get a collection of all the lowest level groups (or leaves if we'll look at this as a tree).
I wrote the following code. Is it inefficient?
public static class FeatureWeightGroupExtensions
{
public static IEnumerable<IFeatureWeightGroup> GetLeafGroups(this IFeatureWeightGroup featureWeightGroup)
{
return GetLeafGroupsRecursive(featureWeightGroup).ToList();
}
private static IEnumerable<IFeatureWeightGroup> GetLeafGroupsRecursive(IFeatureWeightGroup featureWeightGroup)
{
if (!featureWeightGroup.ChildGroups.Any())
return Enumerable.Repeat(featureWeightGroup, 1);
return featureWeightGroup.ChildGroups.Aggregate(Enumerable.Empty<IFeatureWeightGroup>(),
(allGroups, group) =>
allGroups.Concat(GetLeafGroupsRecursive(group)));
}
}