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
Use the ThenBy
method:
var query = product.OrderByDescending(m => m.ProductScore)
.ThenBy(m => m.ProductId);
There's also a ThenByDescending
method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With