Convert SQL to linq expression with counter

I am trying to convert the following SQL to a LINQ expression

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

and I try to follow this webpage as an example:
SQL conversion containing top, count, group and order to LINQ (2 objects)

I got it so far, but I'm stuck in understanding the new part

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

Thank you in advance for your help.


UPDATE:
can you explain what g.Key is? I don’t understand where this variable came from, or what does it also mean? I mean, what if I group 4 different things? How can I address each of them?

 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() }; 
+4
source share
2 answers

The following is the LINQ statement:

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

Note that the Key Property will contain the value of the property that you are grouping, in this case MyCode.

+6
source
 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 } 

prints the same result as your sql in linqpad

0
source

Source: https://habr.com/ru/post/1306965/


All Articles