2010-04-14 22 views
4

我嘗試轉換下面的SQL LINQ表達成LINQ表達式轉換SQL與計數

SELECT COUNT(ID) AS Count, MyCode 
FROM  dbo.Archive 
WHERE  DateSent>[email protected] AND DateSent<[email protected] 
GROUP BY MyCode 

,我一直努力遵循這個網頁爲例:
Converting SQL containing top, count, group and order to LINQ (2 Entities)

我得到這個目前爲止,但我堅持瞭解新的部分

var res = (from p in db.Archives 
      where (p.DateSent>= dateStartMonth) && (p.DateSent< dateToday) 
      group p by p.MyCode into g 
      select new { ??????MyCode = g.something?, MonthlyCount= g.Count() }); 

在此先感謝幫助


UPDATE:
你能解釋g.Key是什麼?我不明白這個變量來自哪裏或者它指的是什麼?我的意思是如果我對4種不同的東西進行分組?我將如何參考每一個?

var res = from archive in db.Archives 
     where archive.DateSent >= dateStartMonth && 
      archive.DateSent < dateToday 
     group archive by archive.MyCode, archive.Extra into archiveGrp 
     select new 
     { 
      MyCode = archiveGrp.Key, 
      Extra = archiveGrp.??? 
      MonthlyCount = archiveGrp.Count() 
     }; 

回答

6

下LINQ的語句應該工作:

var res = from archive in db.Archives 
      where archive.DateSent >= dateStartMonth && 
       archive.DateSent < dateToday 
      group archive by archive.MyCode into archiveGrp 
      select new 
      { 
       MyCode = archiveGrp.Key, 
       MonthlyCount = archiveGrp.Count() 
      }; 

注意,Key property將包含屬性的值,你小組,在這種情況下mycode的。

0
from p in archive 
where p.DateSent >= dateStartMonth && p.DateSent < dateToday 
group p by p.MyCode into g 
select new { Count = g.Count(), MyCode = g.Key } 

產生相同的輸出爲您的SQL在Linqpad