2010-11-22 60 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] 
...