Firstly, I've found a solution to my problem. The question is - is there a better way?
I needed to retrieve a list of Order counts for a period (7 days), such as using a group by. On some days there are no orders, which would mean those days would be eliminated from a group by.
This is what I needed to achieve (using a Kendo UI bar chart):
I've done this in 2 stages. The first to create an Enumeration of the days, then secondly to retrieve the count of Orders from the database.
Notes: db is an Entity Framework data context. DbFunctions.TruncateTime() is used to compare only the date, ignoring the time part).
var from = DateTime.Now.AddDays(-6);
var to = DateTime.Now;
var days = Enumerable.Range(0, 1 + to.Subtract(from).Days)
.Select(offset => from.AddDays(offset))
.ToArray();
var data = days
.Select(i => new
{
Day = i.ToShortDateString(),
Orders = db.Orders.Count(d => DbFunctions.TruncateTime(o.OrderDate) == i.Date)
});
Can it be done better? To retrieve a count/sum of items over the last 7 days?