C# 使用实体框架“按 Col1、Col2 排序”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1700587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Order by Col1, Col2" using entity framework
提问by Lasse Edsvik
I need to order by 2 columns using the entity framework.
我需要使用实体框架按 2 列排序。
How is that done?
这是怎么做的?
return _repository.GetSomething().OrderBy(x => x.Col1 .. Col2)?
i.e
IE
SELECT * FROM Foo ORDER BY Col1, Col2
采纳答案by Konamiman
Try OrderBy(x => x.Col1).ThenBy(x => x.Col2)
. It is a LINQ feature, anyway, not exclusive to EF.
试试OrderBy(x => x.Col1).ThenBy(x => x.Col2)
。无论如何,它是一个 LINQ 功能,并不是 EF 独有的。
回答by parfilko
Another way:
其它的办法:
qqq.OrderBy(x => new { x.Col1, x.Col2} )
回答by hojjat.mi
Try:
尝试:
OrderBy(x => x.Col1).ThenBy(x => x.Col2)
For order by descending try this:
对于降序排序试试这个:
OrderByDescending (x => x.Col1).ThenByDescending (x => x.Col2)
回答by lukyer
Please note, this will not work with Telerik's Grid or any other Telerik's DataSource component. Although it uses prefiltered IQueryable object, sorting is always done automatically as last step effectively overriding your sorting settings.
请注意,这不适用于 Telerik 的 Grid 或任何其他 Telerik 的 DataSource 组件。尽管它使用预过滤的 IQueryable 对象,但排序总是自动完成,作为有效覆盖排序设置的最后一步。
You have to follow: Specifying default sort in grid
您必须遵循:在网格中指定默认排序
回答by e03050
Following sorting happens in the DB level. Not on the returned result.
以下排序发生在 DB 级别。不在返回的结果上。
Try:
尝试:
IQueryable<a>.OrderBy("col1 asc, col2 asc")
Example 1:
示例 1:
ctx.CateringOrders.OrderBy("Details.DeliveryDate asc, Details.DeliveryTime asc")
Example 2:
示例 2:
ctx.CateringOrders.OrderBy("{0} {1}, {2} {3}",
"Details.DeliveryDate", "asc",
"Details.DeliveryTime", "asc"
)
Where
IQueryable<a>
is entity query,
"col1 asc"
is column 1 and sorting direction
"col2 asc"
is column 2 and sorting direction
哪里
IQueryable<a>
是实体查询,
"col1 asc"
是第1列,排序方向
"col2 asc"
是第2列,排序方向