views:

2283

answers:

2

I have a table with a datetime field. I want to retrieve a result set grouped by the month/year combination and the number of records that appear within that month/year. How can this be done in LINQ?

The closest I've been able to figure out is in TSQL:

select substring(mo,charindex(mo,'/'),50) from (
select mo=convert(varchar(2),month(created)) + '/' + convert(varchar(4), year(created)) 
 ,qty=count(convert(varchar(2),month(created)) + '/' + convert(varchar(4), year(created)))
from posts 
group by convert(varchar(2),month(created)) + '/' + convert(varchar(4), year(created))
) a
order by substring(mo,charindex(mo,'/')+1,50)

But I wouldn't say that works...

+2  A: 

This Site has an example that should fill your need.

This is the basic syntax:

from o in yg
group o by o.OrderDate.Month into mg
select new { Month = mg.Key, Orders = mg }
Jimmie R. Houts
+11  A: 
var grouped = from p in posts
     group p by new { month = p.Create.Month,year= p.Create.Year } into d
     select new { dt = string.Format("{0}/{1}",d.Key.month,d.Key.year), count = d.Count() };

Here's the list of DateTime functions available in LINQ. For this to work you'll also need to understand multi-column grouping

ordered descending

var grouped = (from p in posts 
  group p by new { month = p.Create.Month,year= p.Create.Year } into d 
  select new { dt = string.Format("{0}/{1}",d.Key.month,d.Key.year), count = d.Count()}).OrderByDescending (g => g.dt);
Jeremy
i want to sort this by months like first current month at top and previous month next a nd so on?? please help
Praveen Prasad
you can do that by adding an orderbydescending
Jeremy