0

我想使用 for 循环从数据库中计算每天的数据。在这里,我不知道从唯一日期的值中获取一天的开始(从上午 12 点开始)和当天的结束(下午 12 点)。在下面的代码中 startDate 和 endDate 只有日期值,例如 2/11/2012。

for (DateTime dates = startDate; dates <= endDate; dates.AddDays(1))
{
    DateTime BeginingOfDay = begining of value variable dates; // 2/2/2012 00:00:00
    DateTime EndOfDay =  at end of value variable dates; // 2/2/2012 23:59:59
    int count = (from u in db.CDRs where (u.StartTime >= BeginingOfDay && u.StartTime <= EndOfDay) select u).Count();;

    dictionary.Add(dates.ToString("MM/dd/yyyy"), count);
 }
4

2 回答 2

2

处理此问题的最佳方法是使用小于/大于运算符的正确组合n,以及当日午夜和当日午夜n+1

所以给了一天,例如

var date = new Date(2012,8,24); // today

那天午夜(一天的开始)

var start = new Date(date.Year, date.Month, date.Day, 0,0,0); // could also be date.Date

并在第二天获得午夜只需添加 1 天

var end = start.AddDays(1);

现在使用大于或等于开始,小于结束:

var inRange = x.StartTime>=start && x.EndTime<end

放在你的例子中就变成了:

for (DateTime dates = startDate; dates <= endDate; dates.AddDays(1))
{
    DateTime BeginingOfDay = new DateTime(dates.Year,dates.Month,dates.Day,0,0,0);
    DateTime EndOfDay =  BeginingOfDay.AddDays(1);
    int count = (from u in db.CDRs where (u.StartTime >= BeginingOfDay && u.StartTime < EndOfDay) select u).Count();;

    dictionary.Add(dates.ToString("MM/dd/yyyy"), count);
}
于 2012-08-24T08:40:19.773 回答
1

这应该会给你你想要的结果:

using(var dataContext = new YourDataContext())
{
    var dictionary = dataContext.CDRs.GroupBy(u => new
    {
        u.StartTime.Year,
        u.StartTime.Month,
        u.StartTime.Day
    })
    .Select(g => new{ Date = g.Key, Count = g.Count() })
    .ToDictionary(g => new DateTime(g.Key.Year, g.Key.Month, g.Key.Day), g=>g.Count);
    return dictionary;
}
于 2012-08-24T08:57:31.513 回答