Mapping a flat list to a hierarchical list with parent IDs C#

前端 未结 4 1957
感情败类
感情败类 2020-12-17 19:55

I have a flat list of categories as shown in the following classes

public class FlatCategoryList
{
    public List Categories { get; set;         


        
4条回答
  •  心在旅途
    2020-12-17 20:37

    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 };
    }
    

提交回复
热议问题