I have a flat list of categories as shown in the following classes
public class FlatCategoryList
{
public List<FlatCategory> Categories { get; set; }
}
public class FlatCategory
{
public string ID { get; set; }
public string Name { get; set; }
public string ParentID { get; set; }
}
I'm trying to map my flat list of categories to a heirarical structure such as shown below:
public class HieraricalCategoryList
{
public List<Category> Categories { get; set; }
}
public class Category
{
public string ID { get; set; }
public string Name { get; set; }
public string ParentID { get; set; }
public List<Category> ChildCategories { get; set; }
}
My question is, what is the best way to achieve this, given the fact that there could be an infinite number child tiers?
public HieraricalCategoryList MapCategories(FlatCategoryList flatCategoryList)
{
var hieraricalCategoryList = new HieraricalCategoryList();
//Do something here to map the flat category list to the hierarichal one...
return hieraricalCategoryList;
}
public HieraricalCategoryList MapCategories(FlatCategoryList flatCategoryList)
{
var categories = (from fc in flatCategoryList.Categories
select new Category() {
ID = fc.ID,
Name = fc.Name,
ParentID = fc.ParentID
}).ToList();
var lookup = categories.ToLookup(c => c.ParentID);
foreach(var c in categories)
{
// you can skip the check if you want an empty list instead of null
// when there is no children
if(lookup.Contains(c.ID))
c.ChildCategories = lookup[c.ID].ToList();
}
return new HieraricalCategoryList() { Categories = categories };
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With