Example that flattens a nested and, possibly infinite, hierarchical list of child elements.
class Program
{
static void Main(string[] args)
{
// Create dummy categories - not especially pretty
var categories = new List();
categories.AddRange(new List()
{
new Category(){ Id = 1, Name = "Cat1", Children = new List()
{
new Category(){ Id = 101, Name = "Subcat1"},
new Category(){ Id = 102, Name = "Subcat2"},
new Category(){ Id = 103, Name = "Subcat3WithChildren", Children = new List()
{
new Category() { Id = 10301, Name = "Subcat1-sub1" },
new Category() { Id = 10302, Name = "Subcat1-sub2" }
}
}
}},
new Category() { Id = 2, Name = "Cat2"}
});
// Flatten the nesteded list of *child* categories
var flatCategories = new List();
foreach (var rootCategory in categories)
flatCategories.AddRange(IterateChildCategories(rootCategory));
// Spit out the results
foreach (var cat in flatCategories)
Console.WriteLine(cat.Name);
Console.ReadKey();
}
///
/// Iterates through a list of child categories.
///
///
/// Note that this skips the parent categories, and focusses only on the children.
///
private static IEnumerable IterateChildCategories(Category parent)
{
if (parent.Children == null) yield break;
foreach (var g in parent.Children)
{
yield return g;
foreach (var sub in IterateChildCategories(g))
yield return sub;
}
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public List Children { get; set; }
public Category()
{
this.Children = new List();
}
}
}