VSB
VSB

Reputation: 10375

C# Linq-to-SQL: find childrens up to three levels

I have a shop with categories stored in database like below:

enter image description here

Categories are nested in each other using ParentCategoryId and root parent ID is 0.

I want to know how can I retrieve list of categories at most up to 3 levels not more than that?
Note: A thing that is important for me is that the number of maximum level can be adjustable if possible by a input parameter.

Upvotes: 1

Views: 77

Answers (1)

Marko Juvančič
Marko Juvančič

Reputation: 5890

What about a loop for each level?

public void GetCategories(int level) {
   var categories = db.Categories.Where(c => c.ParentCategoryId == 0).ToList();
   var parents = categories.Select(c => c.Id);
   for (var ii = 0; ii < level; ii++) {
      var newCategories = db.Categories.Where(c => parents.Contains(c.ParentCategoryId).ToList();  
      parents = newCategories.Select(c => c.Id);
      categories = categories.Concat(newCategories);
}

   var result = categories;
}

I presumed you need all levels, not just the last one.

Upvotes: 1

Related Questions