我想使用for循环从数据库计算每天的数据。在这里,我不知道从唯一的日期值开始(从上午12点开始)到当天(下午12点)结束。在下面的代码中,startDate和endDate只有日期值,例如2012年2月11日
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);
}
答案 0 :(得分:2)
处理此问题的最佳方法是使用lessthan / greaterthan运算符与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);
}
答案 1 :(得分: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;
}