160

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
Lasse Edsvik
  • 9,070
  • 16
  • 73
  • 109

5 Answers5

327

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

Konamiman
  • 49,681
  • 17
  • 108
  • 138
65

Another way:

qqq.OrderBy(x => new { x.Col1, x.Col2} )
parfilko
  • 1,308
  • 11
  • 12
  • How do you order descending this way? – user551113 Mar 31 '15 at 12:57
  • 11
    qqq.OrderByDescending(x => new { x.Col1, x.Col2} ) – parfilko Mar 31 '15 at 16:30
  • 9
    I get an "At least one object must implement IComparable" error message when used with EntityFramework Core on two string fields. – olivierr91 Nov 20 '17 at 21:20
  • Note, I came here looking for EF Core, so this error is probably exclusive to that but: _"Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access. [uk.ac.sahfos.cpr.console.web]csharp(CS0746)"_ – Auspex Oct 15 '20 at 12:36
42

Try:

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

For order by descending try this:

OrderByDescending (x => x.Col1).ThenByDescending (x => x.Col2)
Sabyasachi Mishra
  • 1,677
  • 2
  • 31
  • 49
hojjat.mi
  • 1,414
  • 16
  • 22
6

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

e03050
  • 1,392
  • 15
  • 12
-7

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: Specifying default sort in grid

Community
  • 1
  • 1
lukyer
  • 7,595
  • 3
  • 37
  • 31