Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Order by Col1, Col2" using entity framework

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
like image 956
Lasse Edsvik Avatar asked Nov 09 '09 12:11

Lasse Edsvik


4 Answers

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

like image 80
Konamiman Avatar answered Oct 22 '22 17:10

Konamiman


Another way:

qqq.OrderBy(x => new { x.Col1, x.Col2} )
like image 44
parfilko Avatar answered Oct 22 '22 19:10

parfilko


Try:

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

For order by descending try this:

OrderByDescending (x => x.Col1).ThenByDescending (x => x.Col2)
like image 43
hojjat.mi Avatar answered Oct 22 '22 18:10

hojjat.mi


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

like image 5
e03050 Avatar answered Oct 22 '22 19:10

e03050