我有Item
班
public class Item {
//...
public DateTime CreateDate { get; set; }
public DateTime EndDate { get; set; }
}
在方法中,我有List<Item> items
。如何比在列表中循环更简洁地查询日期差异的平均值?
double days = 0;
int total = 0;
foreach (var @t in results)
{
if (@t.EndDate != null)
{
total++;
TimeSpan ts = (TimeSpan)(@t.EndDate - @t.CreateDate);
days = ts.TotalDays;
}
}
double avg = days / total;
答案 0 :(得分:6)
var avg = results.Average( x => (x.EndDate - x.CreateDate).TotalDays );
过滤掉空EndDate
值并假设CreateDate不属于DateTime?
类型的版本:
var avg = results.Where( x=> x.EndDate.HasValue)
.Average( x => (x.EndDate.Value - x.CreateDate).TotalDays );
有人要求以dd:HH:ss
的格式格式化持续时间。为此,我们应该平均总毫秒(或秒),并执行以下操作:
var avg = results.Where(x=> x.EndDate.HasValue && x.CreateDate.HasValue)
.Average( x => (x.EndDate.Value - x.CreateDate.Value).TotalMilliseconds );
var fancyOutput = TimeSpan.FromMilliseconds( avg );
Response.Write( fancyOutput.ToString() );