Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to express in LINQ, an SQL OrderBy clause over two fields

I need to write the following SQL statement in LINQ lambdas:

SELECT *
FROM product
ORDER BY ProductScore DESC, ProductID ASC

I guess this code:

product.OrderByDescending(m => m.ProductScore).OrderBy(m => m.ProductId)

it is not equivalent since the second OrderBy will overwrite the first one. Is there any equivalent? Thanks

like image 598
CiccioMiami Avatar asked Mar 21 '12 13:03

CiccioMiami


2 Answers

Use the ThenBy method:

var query = product.OrderByDescending(m => m.ProductScore)
                   .ThenBy(m => m.ProductId);

There's also a ThenByDescending method.

like image 148
Ahmad Mageed Avatar answered Oct 12 '22 02:10

Ahmad Mageed


Yes, you use ThenBy:

product.OrderByDescending(m => m.ProductScore).ThenBy(m => m.ProductId)

(and likewise ThenByDescending). That's the Queryable.ThenBy link; there's an equivalent on Enumerable of course.

In a query expression, this would be:

var query = from product in db.Products
            orderby product.ProductScore descending, product.ProductId
            select product;

ThenBy and ThenByDescending can only be called on IOrderedQueryable / IOrderedEnumerable... see my Edulinq blog post on this for more information.

like image 41
Jon Skeet Avatar answered Oct 12 '22 03:10

Jon Skeet