I found in this stackoverflow nice solution for hierarchical grouping.
How can I hierarchically group data using LINQ?
It helped me a lot, but I would like to ask how I can achieve the same result, but without recursion. Honestly I got a problem to convert it, because recursion is here natural approach for me. Anyone can convert this method to not use recursion?
Usage:
var result = customers.GroupByMany(c => c.Country, c => c.City);
Edited:
public class GroupResult
{
public object Key { get; set; }
public int Count { get; set; }
public IEnumerable<GroupResult> SubGroups { get; set; }
public override string ToString()
{ return string.Format("{0} ({1})", Key, Count); }
}
public static class MyEnumerableExtensions
{
public static IEnumerable<GroupResult> GroupByMany<TElement>(
this IEnumerable<TElement> elements,
params Func<TElement, object>[] groupSelectors)
{
if (groupSelectors.Length > 0)
{
var selector = groupSelectors.First();
//reduce the list recursively until zero
var nextSelectors = groupSelectors.Skip(1).ToArray();
return
elements.GroupBy(selector).Select(
g => new GroupResult
{
Key = g.Key,
Count = g.Count(),
SubGroups = g.GroupByMany(nextSelectors)
});
}
return null;
}
}
Thanks in advance