LINQ: Gruppo per mese e anno all'interno di un campo datetime
Domanda
Ho una tabella con un campo datetime. Voglio recuperare un set di risultati raggruppati per la combinazione mese / anno e il numero di record che compaiono all'interno di quel mese / anno. Come può questo essere fatto in LINQ?
Il più vicino che sono stato in grado di capire è 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)
Ma non direi che funziona ...
Soluzione
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() };
Ecco l'elenco delle funzioni disponibili in DateTime LINQ . Per questo lavoro avrete anche bisogno di capire multi-colonna di raggruppamento
ordinato decrescente
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);
Altri suggerimenti
Questo è per coloro che stanno cercando di realizzare gli stessi, ma utilizzando le espressioni lambda.
Supponendo che si dispone già di un insieme di entità e di ogni entità ha DataOrdine come una delle sue proprietà.
yourCollection
// This will return the list with the most recent date first.
.OrderByDescending(x => x.OrderDate)
.GroupBy(x => new {x.OrderDate.Year, x.OrderDate.Month})
// Bonus: You can use this on a drop down
.Select(x => new SelectListItem
{
Value = string.Format("{0}|{1}", x.Key.Year, x.Key.Month),
Text = string.Format("{0}/{1} (Count: {2})", x.Key.Year, x.Key.Month, x.Count())
})
.ToList();
Se non è necessario la raccolta di SelectListItem poi basta sostituire il select con questo:
.Select(x => string.Format("{0}/{1} (Count: {2})", x.Key.Year, x.Key.Month, x.Count()))
si potrebbe fare anche in questo modo
from o in yg
group o by o.OrderDate.ToString("MMM yyyy") into mg
select new { Month = mg.Key, Orders = mg }
Il risultato sarà
{gennaio 2014, 25} {Feb 2015, 15} ecc ...
Questo sito ha un esempio che dovrebbe riempire il vostro bisogno.
Questa è la sintassi di base:
from o in yg
group o by o.OrderDate.Month into mg
select new { Month = mg.Key, Orders = mg }
Ecco una soluzione semplice per raggruppare in DateTime.
List<leaveallview> lav = new List<leaveallview>();
lav = dbEntity.leaveallviews.Where(m =>m.created==alldate).ToList();
dynamic lav1 = lav.GroupBy(m=>m.created.Value.GetDateTimeFormats()).FirstOrDefault().ToList();