【问题标题】:SQL to LINQ orderby specific orderSQL to LINQ orderby 特定顺序
【发布时间】:2013-05-01 08:34:05
【问题描述】:
select Priority, 
  case Priority 
    when 'Medium' then (Count(*)* 100 / (Select Count(*) From #tem where Priority = 'Medium')) 
    when 'High' then (Count(*)* 100 / (Select Count(*) From #tem where Priority = 'High')) 
    when 'Low' then (Count(*)* 100 / (Select Count(*) From #tem where Priority = 'Low')) 
    when 'Critical' then (Count(*)* 100 / (Select Count(*) From #tem where Priority = 'Critical')) 
  end as '% SLM Met' 
from #tem where Bool = 'True' 
group by Priority
order by 
  case Priority
     WHEN 'Critical' THEN 1
     WHEN 'High' THEN 2
     WHEN 'Medium' THEN 3
     WHEN 'Low' THEN 4
   End

我们如何将其转换为 linq..

我想指定这个顺序以便让我的 UI 正确..

【问题讨论】:

    标签: sql linq sql-to-linq-conversion


    【解决方案1】:

    你可以这样写orderby:

    from x in tbl
    orderby (
            x.Priority == "Critical" ? 1 :
            x.Priority == "High"     ? 2 :
            x.Priority == "Medium"   ? 3 :
            x.Priority == "Low"      ? 4 : -1 //-1 when none of the above
            )
    select x;
    

    【讨论】:

      【解决方案2】:

      整个 SQL 可以用一个普通的平均值来简化一点;

      SELECT Priority,100*AVG(CASE WHEN Bool='True' THEN 1.0 ELSE 0.0 END) 
      AS '% SLM Met' 
      FROM Tem
      GROUP BY Priority
      order by 
        case Priority
           WHEN 'Critical' THEN 1 WHEN 'High' THEN 2
           WHEN 'Medium' THEN 3   WHEN 'Low' THEN 4
         End;
      

      ...或者,用 Linq 编写,例如...

      var sortArray = new[] {"Critical", "High", "Medium", "Low"};
      
      var result =
        (from tem in dbContext.Tem
         group tem by tem.Priority
             into priorities
             select new
             {
                 priority = priorities.Key,
                 avg = priorities.Average(x => x.Bool == "True" ? 1 : 0)
             })
         .AsEnumerable()
         .OrderBy(x => (Array.IndexOf(sortArray, x.priority)));
      

      至于排序,这将在数据库服务器上进行选择,在本地机器上进行排序。有了这么少量的数据,我希望这比复杂化生成的 SQL 更快。

      【讨论】:

      • 我很确定 linq2Sql 不支持Array.IndexOf。
      • @Magnus 澄清了一些事情并添加了缺少的 AsEnumerable,尽管排序自然也可以替换为已接受答案中的排序。只是一个额外的观点:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多