I have a column which has double values. I have to calculate the average of the difference between each values upon all the values in the column.
for example: for 1, 2, 3.5 the average is: ( (2-1) + (3.5-2) ) / 2
Is there a linq way to do it or another smart way?
You can use Zip
and Skip
together to create the "difference between adjacent numbers" part, and then the normal average:
var differenceAverage = input.Zip(input.Skip(1), (x, y) => y - x).Average();
This relies upon the ability to read input
twice (and get the same results each time) however - hopefully that's not a problem in your case.
See more on this question at Stackoverflow