如果您想按小时分组并且“呼叫时间”字段是一个DateTime
字段:
var groupQuery = from row in Foundrows.AsEnumerable()
let hour = row.Field<DateTime>("Call Time").Hour
group row by hour into hourGroup
select new {
CallHour = hourGroup.Key,
CallCount = hourGroup.Count()
};
如果要按Date
+的组合进行分组Hour
:
var groupQuery = from row in Foundrows.AsEnumerable()
let date = row.Field<DateTime>("Call Time")
let hour = date.Hour
group row by new{ date, hour } into dateHourGroup
select new {
CallDate = dateHourGroup.Key.date,
CallHour = dateHourGroup.Key.hour,
CallCount = dateHourGroup.Count()
};
编辑:如果它实际上是一个TimeSpan
(看起来是这样),请使用lazyberezovsky的方法:)
您的评论:如果我想使用TryParse
而不是Parse
,我需要在代码中进行哪些更改?
我建议创建一个允许返回 a 的扩展Nullable<TimeSpan>
,然后您可以检查是否HasValue==true
:
public static TimeSpan? TryGetTimeSpan(this string tsString, string format = null)
{
TimeSpan ts;
bool success;
if (format == null)
success = TimeSpan.TryParse(tsString, out ts);
else
success = TimeSpan.TryParseExact(tsString, format, null, TimeSpanStyles.None, out ts);
return success ? (TimeSpan?)ts : (TimeSpan?)null;
}
现在此查询有效地工作并且不使用未记录的副作用(作为TimeSpan
您在查询中使用的局部变量TimeSpan.TryParse
):
var groupQuery = from r in Foundrows.AsEnumerable()
let time = r.Field<string>("CallTime").TryGetTimeSpan()
where time.HasValue
group r by time.Value.Hours into g
select new
{
Hrs = g.Key,
CallCount = g.Count()
};