1

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 }

Stijn Van Antwerpen
  • 1,840
  • 17
  • 42
  • possible duplicate of [LINQ to calculate a moving average of a SortedList](http://stackoverflow.com/questions/5166716/linq-to-calculate-a-moving-average-of-a-sortedlistdatetime-double) – Rawling May 05 '15 at 12:15

1 Answers1

3

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

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939