如果按小時和外地要組「通話時間」是一個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的做法:)
你comment:如果我想用TryParse
代替Parse
,什麼 變化會我需要在代碼中做出?
我建議創建一個擴展,它允許返回一個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;
}
現在這個查詢的工作效率和不使用無證側efects(如您在查詢中使用的TimeSpan.TryParse
本地TimeSpan
變量):
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()
};
是什麼類型'CallTime'是時間跨度?或字符串 – Habib
CallTime是DateTime字段嗎?如果是這樣,你想按小時或按日期+小時分組嗎? –
它是字符串,但可以作爲時間成功地解析 –