0

This query will return a list of categories (and their included products, but the products are not relevant to this question). The categories with ParentId == null will get sorted by SortOrder, but the Children categories will not. As I understand, this is not possible to acheive directly using LINQ, but can be done programmatically "post query".

How?

The query:

List<ProductCategory> DbCategories = _context.ProductCategories
                        .Include(e => e.Children)
                        .Include(e => e.ProductInCategory)
                            .ThenInclude(p => p.Product)
                        .ToList().OrderBy(o => o.SortOrder)
                        .Where(e => e.ParentId == null).ToList();

The result is displayed recursively in an unordered list, like so:

<ul>
  <li>
    Id=1,SortOrder=1,ParentId=null (sorted)
  </li>
  <li>
    Id=2,SortOrder=2,ParentId=null (sorted)
  </li>
  <li>
    Id=3,SortOrder=3,ParentId=null (sorted)
    <ul>
      <li>
        Id=4,SortOrder=2,ParentId=3 (not sorted)
      </li>
      <li>
        Id=5,SortOrder=3,ParentId=3 (not sorted)
      </li>
      <li>
        Id=6,SortOrder=1,ParentId=3 (not sorted)
        <ul>
          <li>
            <!-- ... and so on... nothing gets sorted further on either. -->
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>
Stian
  • 1,522
  • 2
  • 22
  • 52

1 Answers1

1

You can loop over children lists (after your initial query) to sort each of them:

DbCategories.ForEach(cat => cat.Children = cat.Children.OrderBy(c => c.SortOrder).ToList());

Edit: here is the additionnal example lines for the orther entities:

DbCategories.ForEach(prod =>
{
  prod.ProductInCategory = prod.ProductInCategory.OrderBy(p => p.SortOrder).ToList();
  prod.ProductInCategory.ForEach(pr => pr.Product = pr.Product.OrderBy(p => p.SortOrder).ToList());
});
Oxald
  • 837
  • 4
  • 10
  • Thank you. That worked for the "second generation" (children of categories with `ParentId == null`, but subsequent generations are not affected. – Stian Mar 12 '18 at 13:24
  • Actually it's the same solution, but with nested ForEach calls (equivalent to nested foreach loops) – Oxald Mar 12 '18 at 13:31
  • Ah.. But ... how? I'm not a very experienced C# programmer. I have tried googling "nested foreach linq", but every result is about C# `foreach`. – Stian Mar 12 '18 at 13:45
  • 1
    I added a sample line code for sorting "ProductInCategory" and then "Product" – Oxald Mar 12 '18 at 13:48