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

前端 未结 4 1964
感情败类
感情败类 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:40

    A very easy and highly performant way to make this transformation is to create a lookup in which you map ID values to the nodes that should be the children of that ID value. This lookup can be created in a single pass of the nodes. After that you can iterate through all of the nodes again assigning their child collection to be the value of their ID value in the lookup.

    Note that this is simpler if the lookup maps to objects of the type you are converting to, not converting from.

    var lookup = list.Categories
        .Select(category => new Category()
        {
            ID = category.ID,
            Name = category.Name,
            ParentID = category.ParentID,
        })
        .ToLookup(category => category.ParentID);
    
    foreach (var category in lookup.SelectMany(x => x))
        category.ChildCategories = lookup[category.ID].ToList();
    
    var newList = new HieraricalCategoryList()
    {
        Categories = lookup[null].ToList(),
    };
    

提交回复
热议问题