在LINQ中,如何对来自.Include()的数据执行.OrderBy()?

Ral*_*h N 5 c# linq asp.net-mvc

这是我在做什么:

List<Category> categories = 
  db.Categories.Include("SubCategories").OrderBy(c => c.Order).ToList();
Run Code Online (Sandbox Code Playgroud)

我的类别表上有一列称为“订单”,该列仅包含一个整数,该整数为表提供了某种排序顺序。

我的“ SubCategories”表上有同一列...

我想知道在我的子类别表上添加排序的最简单解决方案……

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

我想将其保持为这种LINQ格式...(方法格式)...

请记住,我正在MVC中工作,需要将其作为模型返回到视图。由于AnonymousTypes,我一直遇到错误的麻烦...

spr*_*y76 0

您可以将单个查询拆分为 2 个仅填充上下文的查询:

IQueryable<Category> categoryQuery = db.Categories.Where(c=> /*if needed*/);
List<Category> categories = categoryQuery.OrderBy(c => c.Order).ToList();
categoryQuery.SelectMany(c => c.SubCategories)
  .OrderBy(sub => sub.Order)
  .AsEnumerable().Count(); // will just iterate (and add to context) all results
Run Code Online (Sandbox Code Playgroud)

您甚至不再需要容易出错的字符串“SubCategories”。