5

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

1 回答 1

9
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() );

时间跨度.ToString()

于 2013-05-28T23:28:20.840 回答