2010-11-22 58 views
26

我该如何将其转换为LINQ?在LINQ中选择案例

select t.age as AgeRange, count(*) as Users 
from (
    select case 
    when age between 0 and 9 then ' 0-25' 
    when age between 10 and 14 then '26-40' 
    when age between 20 and 49 then '60-100' 
    else '50+' end as age 
    from user) t 
group by t.age 

谢谢!

+1

可能的重复 - HTTP:// stackoverflow.com/questions/936028/linq-case-statement,http:// sta ckoverflow.com/questions/209924/switch-statement-in-linq,http://stackoverflow.com/questions/436028/linq-to-sql-case-query,http://stackoverflow.com/questions/936028/ linq-case-statement – pavanred 2010-11-22 09:53:59

+0

如果有人遇到这个问题,并想知道“他们之间有什么区别”只有一个是,也许是重复的是:stackoverflow.com/questions/436028/linq-to-sql-case-query和它没有在标题中指定范围,但它是答案。其他人仅限于个案陈述,但在特定情况下。在实际问题中标记的答案与范围没有任何关系,因为问题指定了...所以... – user1040975 2017-08-01 19:20:50

回答

39

也许这个作品:

from u in users 
let range = (u.Age >= 0 && u.Age < 10 ? "0-25" : 
      u.Age >= 10 && u.Age < 15 ? "26-40" : 
      u.Age >= 15 && u.Age < 50 ? "60-100" : 
      "50+") 
group u by range into g 
select new { g.Key, Count=g.Count() }; 
+0

+1哇这在很多方面帮助我! – A1rPun 2014-04-15 08:18:51

0

我不知道如何使用LINQ语句来创建像这样的高效SQL。但您可以使用:

  1. 使用存储过程(或函数),并从LINQ调用存储过程。
  2. Use Direct SQL

当然你可以使用很多内嵌条件语句(? :),但我不认为其结果将是有效的。

11

check this may help you

var query = from grade in sc.StudentGrade 
         join student in sc.Person on grade.Person.PersonID 
             equals student.PersonID 
         select new 
         { 
          FirstName = student.FirstName, 
          LastName = student.LastName, 
          Grade = grade.Grade.Value >= 4 ? "A" : 
             grade.Grade.Value >= 3 ? "B" : 
             grade.Grade.Value >= 2 ? "C" : 
             grade.Grade.Value != null ? "D" : "-" 
         }; 
+1

从另一个复制/粘贴[answer](http://stackoverflow.com/questions/936028/linq-case -statement/936136#936136) – abatishchev 2010-11-22 10:00:33

+0

@ abatishchev- changed我认为它的好例子,但没有probs的答案是由另一个例子更新 – 2010-11-22 10:03:04

4

像这样的事情?

var users = (from u in Users 
      select new 
      { 
       User = u, 
       AgeRange = 
        u.Age >= 0 && u.Age <= 9 ? "0-25" : 
        u.Age <= 14    ? "26-50" : 
        u.Age <= 49    ? "60-100": 
               "50+" 
       }).GroupBy(e => e.AgeRange); 
7

使用类似的东西:

class AgeHelper 
{ 
    private static Dictionary<IEnumerable<int>, string> dic = new Dictionary<IEnumerable<int>, string> 
    { 
     { Enumerable.Range(0, 10), "0-25" }, 
     { Enumerable.Range(10, 5), "26-40" }, 
     { Enumerable.Range(15, 35), "60-100" } 
    }; 

    public string this[int age] 
    { 
     get 
     { 
      return dic.FirstOrDefault(p => p.Key.Contains(age)).Value ?? "50+"; 
     } 
    } 
} 

@ Botz3000的答案的其余部分:

from u in users 
let range = new AgeHelper()[u.Age] 
...