Thursday, December 22, 2011

The Aggregate and Scan RX extension methods.

This post is about how to sum all numbers in a range from an observable sequence with the help of the Aggregate method. Then the FirstOrDefault is used to convert the resulting IObservable to an int.
var sumOfNumbers = Observable.Range(1, 10)
                   .Aggregate(0, (x, y) => x + y)
                   .FirstOrDefault();

Console.WriteLine("Sum of numbers from 1 to 10 is {0}", sumOfNumbers);
==========
Sum of numbers from 1 to 10 is 55
==========
Or you can you the Scan method to display the intermediate results with the help of the Do method and finally store the result with the LastOrDefault.
int sumOfNumbers = Observable.Range(1, 10)
.Scan(0, (x, y) => x + y)
.Do(Console.WriteLine)
.LastOrDefault();

Console.WriteLine("Sum of numbers from 1 to 10 is {0}", sumOfNumbers);
==========
1
3
6
10
15
21
28
36
45
55
Sum of numbers from 1 to 10 is 55
==========
You can use the Aggregate method to fill a collection with received values from the observable:
IList<int> collection = 
    Observable.Range(1, 5)
              .Aggregate(new List<int>(), (list, value) => {
                               list.Add(value);
                            return list;
                         })
              .FirstOrDefault();

foreach (var element in collection)
{
    Console.WriteLine(element);
}
==========
1
2
3
4
5
==========

No comments:

Post a Comment