簡體   English   中英

使用count將SQL轉換為linq表達式

[英]Convert SQL to linq expression with count

我試圖將以下SQL轉換為LINQ表達式

SELECT    COUNT(ID) AS Count, MyCode
FROM      dbo.Archive
WHERE     DateSent>=@DateStartMonth AND DateSent<=@DateEndMonth
GROUP BY  MyCode

我一直試圖關注這個網頁作為例子:
將包含top,count,group和order的SQL轉換為LINQ(2個實體)

到目前為止,我得到了這個,但我仍然堅持理解新的部分

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

在此先感謝您的幫助


更新:
你能解釋一下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() 
      };

下面的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屬性將包含您分組的屬性的值,在本例中為MyCode。

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  }

產生與Linqpad中的Sql相同的輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM