Pergunta

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

How can we convert this into linq..

I want to specify this order so as to get my UI right..

Foi útil?

Solução

You can write the orderby like this:

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;

Outras dicas

The entire SQL can be a bit simplified using a plain average;

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;

...or, written in Linq, for example...

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

As for sorting, this will do the select on the database server and the sorting on the local machine. With this small amount of data, I'd expect that to be faster than complicating the generated SQL.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top