简体   繁体   English

从SQL到LINQ的情况

[英]Case When SQL to LINQ

I am still new to LINQ and trying to convert this SQL command 我还是LINQ的新手,正尝试转换此SQL命令

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 ? 这在SQL中有效,使用LINQ实现此目标的最佳方法是什么?

Edit: Issue Resolved 编辑:已解决的问题

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

使用三元运算符

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM