获取要显示为树的动态对象的嵌套列表

时间:2019-04-16 14:49:47

标签: c# list recursion

我有这两个班

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
}

public class CategoryVm
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<CategoryVm> SubCategories { get; set; }
}

并且我有一个第一类的列表,我想将其转换为第二种形式以在树形视图中显示。


示例输入

enter image description here

示例输出

enter image description here

1 个答案:

答案 0 :(得分:-1)

这是我使用的代码,它可以正常工作

public List<CategoryVm> GetCategoriesTree(List<Category> categoriesList)
{
    var categoriesTree = categoriesList.Where(category => category.ParentCategoryId == null)
        .Select(category => new CategoryVm
        {
            Id = category.Id,
            Name = category.Name,
            SubCategories = new List<CategoryVm>()
        }).ToList();
    foreach (var category in categoriesTree)
    {
        FillSubCategories(category, categoriesList);
    }
    return categoriesTree;
}

private void FillSubCategories(CategoryVm categoryVm, List<Category> categoriesList)
{
    var subCategories = categoriesList.Where(category => category.ParentCategoryId == categoryVm.Id).ToList();
    if (subCategories.Any())
    {
        categoryVm.SubCategories = subCategories.Select(category => new CategoryVm
        {
            Id = category.Id,
            Name = category.Name,
            SubCategories = new List<CategoryVm>()
        }).ToList();
        foreach (var subCategory in categoryVm.SubCategories)
        {
            FillSubCategories(subCategory, categoriesList);
        }
    }
}