0

I have this entity model:

public class ProductCategory
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int SortOrder { get; set; }
    public int? ParentId { get; set; }
    public ProductCategory ParentCategory { get; set; }
    public ICollection<ProductCategory> Children { get; set; } = new List<ProductCategory>();
}

How can I write a LINQ query that sorts a recursive tree structure of categories correctly? This is what I have now:

var categories = _context.ProductCategories
                        .Include(e => e.Children).ToList().OrderBy(o => o.SortOrder)
                        .Where(e => e.ParentId == null)
                        .OrderBy(o => o.SortOrder);

The root categories (with ParentId == null are correctly sorted, but the children are not.

Stian
  • 1,522
  • 2
  • 22
  • 52

0 Answers0