Reputation: 53
Even thought there's another topic with similar title, i search for a more generic answer.
I have a SQLSERVER Query to select userId's with a custom Order By
clause. Something like this:
SELECT userID
FROM users
WHERE userName like '%whatever%'
ORDER BY
CASE
WHEN UserID = 123 THEN 0
WHEN UserID = 456 THEN 1
WHEN UserID = 789 THEN 2
ELSE 3
END ASC,
UserID
So, how do i replicate the same Order By
structure, but using LINQ with LAMBDA in C#?
Here is my code so far:
var userID = db.User.Where(x => x.userName.Contains("whatever").OrderBy(x => x.userID).Select(x => x.userID).ToList();
Upvotes: 1
Views: 424
Reputation: 62238
ORDER BY
CASE
WHEN UserID = 123 THEN 0
WHEN UserID = 456 THEN 1
WHEN UserID = 789 THEN 2
ELSE 3
END ASC,
UserID
is functionally equivalent to this Lambda
.OrderBy(_ => _.userID == 123 ? 0 : _.userID == 456 ? 1 : _.userID == 789 ? 2 : 3)
.ThenBy(_ => _.userID)
Upvotes: 2