-1

I have these two classes

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

and I have a list of the first class and I want to convert it to the second form to be displayed inside a tree view.


Example input

enter image description here

Example output

enter image description here

asked Apr 16, 2019 at 14:49
0

1 Answer 1

0

Here is the code that I used, and it worked properly

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);
 }
 }
}
answered Apr 16, 2019 at 14:50
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.