"Order by Col1, Col2" using entity framework

C#.NetLinqEntity Framework

C# Problem Overview


I need to order by 2 columns using the entity framework.

How is that done?

return _repository.GetSomething().OrderBy(x => x.Col1   .. Col2)?

i.e

SELECT * FROM Foo ORDER BY Col1, Col2

C# Solutions


Solution 1 - C#

Try OrderBy(x => x.Col1).ThenBy(x => x.Col2). It is a LINQ feature, anyway, not exclusive to EF.

Solution 2 - C#

Another way:

qqq.OrderBy(x => new { x.Col1, x.Col2} )

Solution 3 - C#

Try:

OrderBy(x => x.Col1).ThenBy(x => x.Col2)

For order by descending try this:

OrderByDescending (x => x.Col1).ThenByDescending (x => x.Col2)

Solution 4 - C#

Following sorting happens in the DB level. Not on the returned result.

Try:

IQueryable<a>.OrderBy("col1 asc, col2 asc")

Example 1:

ctx.CateringOrders.OrderBy("Details.DeliveryDate asc, Details.DeliveryTime asc")

Example 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

Solution 5 - C#

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.

You have to follow: https://stackoverflow.com/questions/23393506/specifying-default-sort-in-grid

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLasse EdsvikView Question on Stackoverflow
Solution 1 - C#KonamimanView Answer on Stackoverflow
Solution 2 - C#parfilkoView Answer on Stackoverflow
Solution 3 - C#hojjat.miView Answer on Stackoverflow
Solution 4 - C#e03050View Answer on Stackoverflow
Solution 5 - C#lukyerView Answer on Stackoverflow