C# Sql to Linq checking multiple cases

醉酒当歌 提交于 2021-01-04 07:07:43

问题


How to check multiple cases in Linq ( to classify "over paid","under paid","medium pay")

Sql

select id,name,salary,
  case  when salary <=1500 then 'under paid'
        when salary >=3500 then 'over paid'
        else 'medium pay' end as status 
from Person

Linq

   var q =
          context.Persons.
          Select(c => 
          new { 
               EmployeeID = c.Id,
               EmployeeName = c.name,
               EmployeeSalary = c.salary,
               Status = c.salary > 1000 ? "under paid" : "overpaid"
              }
            );

Using ternary operator i can check either or cases.otherwise i have to use if..else if.


回答1:


Status = c.salary < 1000 ? "under paid" : 
         c.salary < 2000 ? "medium paid" :
         c.salary < 3000 ? "not bad paid" :
         "overpaid";

the above essentially means:

If salary is under 1k then return "under paid" else if salary is under 2k then return "medium paid" else if salary is under 3k etc etc

You can stack ternary operators like this. The first one that evaluates to true will be returned and the rest ignored.

Or, just call a friggen method.

new { Status = GetPaymentStatus(c.salary) }

You can call methods from within a linq query.




回答2:


You can nest your ternary operator statements and LINQ will convert it into a CASE statement: http://lancefisher.net/blog/archive/2008/05/07/linq-to-sql---case-statements.aspx




回答3:


I would just write a method and call that from within the selection area.

var q = context.Persons.Select(c => GetStatus(c.salary));


来源:https://stackoverflow.com/questions/1888340/c-sharp-sql-to-linq-checking-multiple-cases

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!