代码之家  ›  专栏  ›  技术社区  ›  user215675

C SQL到LINQ检查多个案例

  •  1
  • user215675  · 技术社区  · 16 年前

    如何在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
    

    林克

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

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

    3 回复  |  直到 16 年前
        1
  •  4
  •   Will    16 年前
    Status = c.salary < 1000 ? "under paid" : 
             c.salary < 2000 ? "medium paid" :
             c.salary < 3000 ? "not bad paid" :
             "overpaid";
    

    上述基本意思是:

    如果工资低于1公里,则返回“欠付”,否则如果工资低于2公里,则返回“中付”,否则如果工资低于3公里等

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

    或者,只需调用一个friggen方法。

    new { Status = GetPaymentStatus(c.salary) }
    

    可以 从Linq查询中调用方法。

        2
  •  2
  •   charoco    16 年前

    可以嵌套三元运算符语句,Linq会将其转换为case语句: http://lancefisher.net/blog/archive/2008/05/07/linq-to-sql---case-statements.aspx

        3
  •  1
  •   Mike Fielden    16 年前

    我只需要编写一个方法并从选择区域内调用它。

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