Posts tagged Accumulator
Refactoring C# Series: Aggregation of IEnumerable
Mar 2nd
I was recently reading Programming Ruby: The Pragmatic Programmers’ Guide, Second Edition, and came across this piece of example Ruby code:
[1,3,5,7].inject(0) {|sum, element| sum+element} -> 16
[1,3,5,7].inject(1) {|product, element| product*element} -> 105
Inject is a method which acts on an array by aggregating or accumulating the values within that array. It loops through the array, and for every item in the array, it performs a function. It then saves the result for the next iteration of the loop and eventually returns the aggregated value.
In C# 1.0 you would probably write such a method like this:
int sum = 0; int[] list = new int[] { 1, 3, 5, 7 }; foreach (int item in list) { // Perform some function, then save the result sum = sum + item; }
It’s a bit long-winded, and if you wanted to make it reusable, you’d have a hard time.
In C# 3.0, you can do it just like you can in Ruby.
