【问题标题】:Select case in LINQ [duplicate]在 LINQ 中选择大小写 [重复]
【发布时间】:2011-05-13 17:48:45
【问题描述】:

我怎样才能把它翻译成 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

谢谢!

【问题讨论】:

标签: c# sql linq tsql linq-to-sql


【解决方案1】:

也许这行得通:

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

【讨论】:

  • +1 哇,这在很多方面帮助了我!
  • 有帮助,但我认为标签,例如“0-25”,不符合条件。
【解决方案2】:

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

【讨论】:

  • 从另一个answer复制/粘贴
  • @abatishchev- 改变了我认为它的好例子,但没有问题的答案被另一个例子更新
【解决方案3】:

使用类似的东西:

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]
...

【讨论】:

    【解决方案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);
    

    【讨论】:

      【解决方案5】:

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

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

      当然你可以使用很多内联条件语句(? :),但我认为结果不会有效率。

      【讨论】:

        猜你喜欢
        • 2014-05-22
        • 2018-05-31
        • 2020-07-25
        • 1970-01-01
        • 2017-05-04
        • 1970-01-01
        • 1970-01-01
        • 2013-06-18
        • 2021-07-16
        相关资源
        最近更新 更多