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;
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 );
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With