As expressed in LINQ, 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 assume this code:

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

it is not equivalent since the second OrderBy will overwrite the first. Is there an equivalent? thanks

+6
source share
4 answers

Use the ThenBy method:

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

There is also a ThenByDescending method.

+12
source

Yes, you are using ThenBy :

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

(and similarly to ThenByDescending ). This is a Queryable.ThenBy link; There is an equivalent on Enumerable , of course.

In the query expression, this will 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 article on this entry for more information .

+3
source

Use ThenBy :

 var query = db.Products .OrderByDescending(m => m.ProductScore) .ThenBy(m => m.ProductId); 
+1
source

to try

 product.OrderByDescending(m => m.ProductScore).ThenBy(m => m.ProductId) 
+1
source

Source: https://habr.com/ru/post/911301/


All Articles