简体   繁体   中英

How to convert SQL query to LINQ with Orderby, Groupby

I am writing to write this SQL query in linq, but didnt work..

select [ProcessTime], Count([ID]) as 'amount of processes'
from [DB].[dbo].[TableX]
where [ID] in ('ServerX', 'ServerY') and [Type] ='Complete'
group by [ProcessTime]
order by [ProcessTime]

I would like to achieve this linq & what I have tried , I split the query into two, one for process time group by clause and another to count the ID's

var query1 =  (from a in this.db.Processes
               where (a.ID =='ServerX' || a.ID =='ServerY') && a.Type =='Complete'
               group a by a.ProcessTime into b
              //here I dont know where to place orderby
               select b);


 var query2 = (from a in this.db.Processes
               where (a.ID =='ServerX' || a.ID =='ServerY') && a.Type =='Complete'
               orderby a.ProcessTime 
               select a).Count();

is this the right way to split the query into two and then later combine them ?

Try this:

var serverNames = new string[]{"ServerX", "ServerY"};
var result = db.Processes
    .Where(p => serverNames.Contains(p.ID) && p.Type == "Complete")
    .GroupBy(p => p.ProcessTime)
    .Select(g => new
    {
        ProcessTime = g.Key,
        AmountOfProcesses = g.Count()
    })
    .OrderBy(x => x.ProcessTime);

You can do all this in one query:

var query1 = (from a in this.db.Processes
              where (a.ID == "ServerX" || a.ID == "ServerY") && a.Type == "Complete"
              group a by a.ProcessTime into b
              orderby b.Key
              select new {ProcessTime = b.Key, Count = b.Count()});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM