Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In LINQ, how can I do an .OrderBy() on data that came from my .Include()?

Here's what I'm doing:

List<Category> categories = 
  db.Categories.Include("SubCategories").OrderBy(c => c.Order).ToList();

I have a column on my categories table called "Order" which simply holds an integer that gives the table some kind of sorting order.

I have the same column on my "SubCategories" table...

I want to know the simplest solution to add the sort on my subcategories table... something like:

List<Category> categories = 
  db.Categories.Include("SubCategories").OrderBy(c => c.Order)
     .ThenBy(c => c.SubCategories as x => x.Order).ToList();

I'd like to keep it in this type of LINQ format... (method format)...

Keep in mind, i'm working in MVC and need to return it to a view as a model. I've been having trouble with errors because of AnonymousTypes...

like image 970
Ralph N Avatar asked Nov 25 '22 07:11

Ralph N


1 Answers

I'm not sure if this is supported, but here's how it might be done:

List<Category> categories = 
  db.Categories.Include(c => c.SubCategories.OrderBy(s => s.Order)).OrderBy(c => c.Order)

The Include method now supports Expressions like this, but I'm not certain if it supports ordering too.

You might be better off sorting the subcategories when you use them, probably in your view.

For example:

@for (var cat in Model.Categories) {
   @cat.Name
   @for (var sub in cat.SubCategories.OrderBy(c => c.Order) {
       @sub.Name
   }
}
like image 191
Scott Rippey Avatar answered Jan 08 '23 19:01

Scott Rippey