Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get average of the difference in datetime columns?

I have an Item class

public class Item {
    //...
    public DateTime CreateDate { get; set; }
    public DateTime EndDate { get; set; }
}

In a method, I have List<Item> items. How would I query average of date differences in days more succinctly than looping through the list?

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;
like image 508
Josh Avatar asked May 28 '13 23:05

Josh


1 Answers

var avg = results.Average( x => (x.EndDate - x.CreateDate).TotalDays );

Version that filters out null EndDate values and assuming that CreateDate is not of type DateTime?:

var avg = results.Where( x=> x.EndDate.HasValue)
    .Average( x => (x.EndDate.Value - x.CreateDate).TotalDays );

Edit

It was asked out to format the duration in the format of dd:HH:ss. To do that, we should average the total milliseconds (or seconds) and do something like:

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

like image 128
Thomas Avatar answered Oct 03 '22 14:10

Thomas