using System; using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var samples = new[] { new Category { Id = 1, ParentCategoryId = 8, SortOrder = 1, Text = "Firefall" }, new Category { Id = 2, ParentCategoryId = 8, SortOrder = 2, Text = "Left 4 Dead 2" }, new Category { Id = 3, ParentCategoryId = 8, SortOrder = 3, Text = "Renegade X" }, new Category { Id = 4, ParentCategoryId = 2, SortOrder = 2, Text = "Survival" }, new Category { Id = 5, ParentCategoryId = 0, SortOrder = 1, Text = "General" }, new Category { Id = 6, ParentCategoryId = 8, SortOrder = 4, Text = "Battlefield 4" }, new Category { Id = 7, ParentCategoryId = 2, SortOrder = 1, Text = "Versus" }, new Category { Id = 8, ParentCategoryId = 0, SortOrder = 2, Text = "Games" }, new Category { Id = 9, ParentCategoryId = 0, SortOrder = 3, Text = "Army Restricted Area" }, new Category { Id = 10, ParentCategoryId = 9, SortOrder = 1, Text = "Kool Kids Klub" } }; var categories = new List(samples); // hierarchycal var categoryTree = CategoryTree.Create(categories, o => o.ParentCategoryId == 0); // recursively called Console.WriteLine on every node PrintNodes(categoryTree); Console.WriteLine(new string('-',80)); var flatTree = categoryTree.Flatten(); foreach(var category in flatTree) { Console.WriteLine(category.DisplayText); } } public static void PrintNodes(CategoryTree tree) { if (tree == null || !tree.Any()) return; foreach(var node in tree) { Console.WriteLine(node.DisplayText); PrintNodes(node.Children); } } } public class Category { public int Id { get; set; } public int ParentCategoryId { get; set; } public int SortOrder { get; set; } public string Text { get; set; } } public class CategoryNode : Category { public CategoryNode(Category category) { Id = category.Id; ParentCategoryId = category.ParentCategoryId; SortOrder = category.SortOrder; Text = category.Text; } public CategoryTree Children { get; set; } public int Level { get; set;} public string DisplayText { get { return string.Concat(new string('.', Level*2), Text); } } } public class CategoryTree : IEnumerable { private List innerList = new List(); public CategoryTree(IEnumerable nodes) { innerList = new List(nodes); } public IEnumerator GetEnumerator() { return innerList.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public IEnumerable Flatten() { foreach(var category in innerList.OrderBy(o => o.SortOrder)) { yield return category; if (category.Children != null) { foreach(var child in category.Children.Flatten()) { yield return child; } } } } public static CategoryTree Create(IEnumerable categories, Func parentPredicate, int level = 0) { var nodes = categories .Where(parentPredicate) .OrderBy(o => o.SortOrder) .Select(item => new CategoryNode(item) { Level = level, Children = Create(categories, o => o.ParentCategoryId == item.Id, level + 1) }); return new CategoryTree(nodes); } }