LINQ to SQL:在提供的范围内为每个日期选择计数行?

时间:2011-10-24 14:25:11

标签: c# linq linq-to-sql

我有一个表帐户,其中包含一个名为CreatedOn(可为空的日期时间)的列。

我正在编写一个从(和DateTime对象)获取两个参数的方法,我想选择from和to之间的所有日期以及在每个日期创建的T中的行数。 / p>

如何在LINQ中以优雅有效的方式完成此操作?

我尝试这样做,但它似乎在列表日期的每个日期查询数据库一次:

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);
}

1 个答案:

答案 0 :(得分:3)

更新了对评论的回复

我不会说它很优雅,但它只会查询数据库一次。

static void Test(DataClasses1DataContext context, DateTime fromDate, DateTime toDate)
{
    var result = context.Accounts
                .Where(p => p.CreatedOn >= fromDate && p.CreatedOn <= toDate)
                .GroupBy(x => x.CreatedOn.Date)
                .Select(x => new {
                   dt = x.Key,
                   count = x.Count()});
}

List<DateTime> dates = new List<DateTime>();
while (fromDate <= toDate)
{
    dates.Add(fromDate.Date);
    fromDate = fromDate.AddDays(1);
}    

var allDates = dates.Select(x => new {
                    dt = x,
                    count = 0});

// Merge both lists and then filter to include highest count
var result = rows.Concat(allDates)
                 .GroupBy(x => x.dt)
                 .Select(x => new {
                    dt = x.Key,
                    count = x.OrderByDescending(c => c.count)
                             .FirstOrDefault().count});