I have a table Account with a column called CreatedOn (nullable datetime).
I'm writing a method that takes two parameters from and to (DateTime objects) and I want to select all the dates between from and to along with the number of rows in T that where created on each of those dates.
How can I do this in an elegant and effective way in LINQ?
I tried to do it this way, but it seems to query the database once for each date in the list dates:
static void Test(DataClasses1DataContext context, DateTime from, DateTime to)
{
List<DateTime> dates = new List<DateTime>();
while (from <= to)
{
dates.Add(from.Date);
from = from.AddDays(1);
}
var result = dates.Select(d => new { Date = d, Count = context.Accounts.Count(a => a.CreatedOn.HasValue && a.CreatedOn.Value.Date == d) });
foreach (var row in result)
Console.WriteLine(row.Date + " " + row.Count);
}