Str8UpRippin
Str8UpRippin

Reputation: 69

Case When SQL to LINQ

I am still new to LINQ and trying to convert this SQL command

Id     | TitleName
------ | ------
1      | Accounts
2      | Buyer
3      | Engineer
4      | Other
5      | Apple  


SELECT Id, TitleName

    FROM dbo.Title

       ORDER BY 

         CASE WHEN TitleName = 'Other'

            THEN 0 ELSE 1 END DESC, TitleName ASC

This selects the table and ascends it in alphabetical order

Then it grabs 'Other' and forces it to the bottom.

So it ends up like this

Id     | TitleName
------ | ------
1      | Accounts
5      | Apple  
2      | Buyer
3      | Engineer
4      | Other

This works in SQL, What is the best approach to achieve this using LINQ ?

Edit: Issue Resolved

  var queryAllCustomerTitle = from cust in _titleRepository.Table
                              orderby cust.TitleName == "Other" ? 1 : 0, cust.TitleName
                              select cust;

Upvotes: 1

Views: 101

Answers (1)

M B
M B

Reputation: 2326

use the ternary operator

OrderByDescending(a=>a.TitleName == "Other" ? 0:1).ThenBy(a=>a.TitleName)

Upvotes: 2

Related Questions