C#SQL to Linq检查多种情况 [英] C# Sql to Linq checking multiple cases

查看:32
本文介绍了C#SQL to Linq检查多种情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Linq中检查多个案件(将超额支付",欠付",中等支付"分类)

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"
              }
            );

使用三元运算符,我可以检查一个或多个case.否则,我必须使用if..else if.

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

推荐答案

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

以上本质上是指:

如果薪水低于1k,则返回薪水不足";否则,如果薪水低于2k,则返回中等薪水",否则,如果薪水低于3k,以此类推

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

您可以像这样堆叠三元运算符.将返回第一个计算结果为true的值,其余的将被忽略.

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

或者,只需调用friggen方法.

Or, just call a friggen method.

new { Status = GetPaymentStatus(c.salary) }

可以从linq查询中调用方法.

You can call methods from within a linq query.

这篇关于C#SQL to Linq检查多种情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆