获取datetime列的差异的平均值?

时间:2013-05-28 23:04:52

标签: c# linq linq-to-sql

我有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;

1 个答案:

答案 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() );

TimeSpan.ToString()