Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
ToList(TSource) Method
Collapse the table of content
Expand the table of content

Observable.ToList(TSource) Method

Creates a list from an observable sequence.

Namespace:  System.Reactive.Linq
Assembly:  System.Reactive (in System.Reactive.dll)

static member ToList : 
        source:IObservable<'TSource> -> IObservable<IList<'TSource>> 

Type Parameters


The type of source.


Type: System.IObservable(TSource)
The source observable sequence to get a list of elements for.

Return Value

Type: System.IObservable(IList(TSource))
A list from an observable sequence.

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type IObservable(TSource). When you use instance method syntax to call this method, omit the first parameter. For more information, see https://msdn.microsoft.com/en-us/library/bb384936(v=vs.103).aspx or https://msdn.microsoft.com/en-us/library/bb383977(v=vs.103).aspx.

The ToList operator takes all the items in the sequence and puts them in a list. Then the list is returned as an observable sequence (IObservable<IList<TSource>>). The return value of this operator differs from the corresponding operator on IEnumerable in order to retain asynchronous behavior.

The following example uses the Generate operator to generate a simple sequence of the integers (1-10). Then, the ToList operator is used to convert that sequence to a list. The IList.Add method is used to 9999 to the resulting list before each item in the list is written to the console window.

using System;
using System.Reactive.Linq;
using System.Collections;

namespace Example
  class Program
    static void Main()
      //*** Generate a sequence of integers 1-10  ***//

      var obs = Observable.Generate(1,            // Initial state value
                                    x => x <= 10, // The termination condition. Terminate generation when false (the integer squared is not less than 1000)
                                    x => ++x,     // Iteration step function updates the state and returns the new state. In this case state is incremented by 1 
                                    x => x);      // Selector function determines the next resulting value in the sequence. The state of type in is squared.

      //*** Convert the integer sequence to a list. Use the IList.Add() method to add 9999 to the list  ***//

      var obsList = obs.ToList();

      obsList.Subscribe(x => 

        //*** Enumerate the items in the list  ***//

        foreach (int val in x)

      Console.WriteLine("\nPress ENTER to exit...\n");

The following output was generated with the example code.


Press ENTER to exit...

© 2015 Microsoft