Entity Framework groupby day to day in month

c# entity-framework-6 linq

Question

I'm trying to do a groupby from the 16th of each months to the 15th of the next months.

Is it possible with Entity Framework or linq?

var result = await db.Orders.Where(o => o.OrderDate > date)
                            .GroupBy(...)
                            .ToListAsync();
1
2
1/15/2019 6:23:33 PM

Accepted Answer

To make this work with EF and SQL, you can just do some date math to compute a "period" number for grouping. Basically, you convert each date to the month, offset by the 16th, plus add an offset for the year:

var result = await db.Orders.Where(o => o.OrderDate > date)
                            .GroupBy(o => o.OrderDate.Month + 12*(o.OrderDate.Year - date.Year) - (o.OrderDate.Day >= 16 ? 0 : 1))
                            .ToListAsync();

Per @stuartd, here is how to get back the period for each group:

var resultp = result.Select(r => new {
                  PeriodBegin = new DateTime(date.Year + r.Key / 12 - (r.Key % 12 == 0 ? 1 : 0), r.Key % 12 == 0 ? 12 : r.key % 12, 16),
                  PeriodEnd = new DateTime(date.Year + r.Key / 12, r.Key % 12 + 1, 15),
                  Orders = r.ToList()
              }).ToList();
1
1/15/2019 11:12:14 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow