C# LINQ TimeSpan Average Days -
i learning linq , want linq query equivalent of following code.
the ienumerable list contains sorted list of dates: oldest newest.
the code below derives timespan
s subtracting array's zeroth element date array's first element date, first element date 2nd, 2nd 3rd , on. timespan.days
averaged elsewhere in code.
i trust linq query not require construction of array. ienumerable<datetime>
structure used data source.
ienumerable<datetime> list; // contains sorted list of oldest newest dates // build datetime array datetime[] datesarray = null; timespan ts; list<int> dayslist = new list<int>(); datesarray = (from dt in list select dt).toarray(); // loop through array , derive timespan subtracting previous date, // contained in previous array element, date in current array element. // start loop @ element 1. (int = 1; < list.count(); i++) { ts = datesarray[i].subtract(datesarray[i - 1]); // ts timespan type dayslist.add(ts.days); // add timespan.days list<int> averaging elsewhere. }
thank you,
scott
i think want:
double averagedays = list .skip(1) .zip(list, (next, prev) => (double)next.subtract(prev).days) .average();
do note lossy average. sure don't want use totaldays
instead?
edit:
the way works overlay sequence 'one-deferred' version of sequence, makes easy calculate consecutive deltas. it's matter of averaging deltas produce result.
for comparison, 'faithful' translation of existing code like:
double averagedays = enumerable .range(1, list.count - 1) .average(i => (double)list[i].subtract(list[i - 1]).days);
Comments
Post a Comment