A LINQ challenge:
I have a ordered list of numbers. assume { 2 , 3 , 5, 7, 11 }
I like to calculate the average between each item and the next. Is there any short way to do this with linq?
so the result in this case should be : { 2.5 , 4, 6, 9 }
A LINQ challenge:
I have a ordered list of numbers. assume { 2 , 3 , 5, 7, 11 }
I like to calculate the average between each item and the next. Is there any short way to do this with linq?
so the result in this case should be : { 2.5 , 4, 6, 9 }
You can use Enumerable.Zip
:
List<int> ints = new List<int> { 2, 3, 5, 7, 11 };
IEnumerable<double> averages = ints.Zip(ints.Skip(1), (i1, i2) => (i1 + i2) / 2d);
This zips the list with itself (starting with the second element due to Skip(1)
).
The result: 2.5 , 4.0, 6.0, 9.0