Home > Mobile >  Calcuate Average Days Between of a List of Dates in C#
Calcuate Average Days Between of a List of Dates in C#

Time:11-28

I have a simple List. Each date is arbitrary, but is in chronlogical order.

I would like to determine the average of day span between dates.

For example:

  • 01/01/2022
  • 01/02/2022
  • 01/04/2022

...should return an average of 1.5. (The denominator in this case is the timespans between dates. In this case, there are only 2 timespans between the 3 dates)

Because there's 1 day between 1/1 and 1/2, and 2 days between 1/2 and 1/4.

(1 day   2 days) / 2 timespans = 1.5 avg

Is there a LINQ way of doing this, without having to manually iterate through each list item in list?

CodePudding user response:

Not sure if there's a better way of doing it, but here's one that I just put together, and it seems to work reliably for me

var avg = myList.Zip(myList.Skip(1), (dt1, dt2) => dt2 - dt1).Average(dt => dt.Days);

EDIT: just checked the docs, and the .Zip method isn't in versions prior to .NET 4

CodePudding user response:

This will do it iterating over the List only once:

Enumerable.Range(1, dates.Count() - 1)
    .Select(i => (dates[i] - dates[i - 1]).TotalDays)
    .Average();

CodePudding user response:

try this

double aveDays= (days.Last()-days.First()).Days /((double)days.Count-1);
    
  • Related