Observable.Where(TSource) Method (IObservable(TSource), Func(TSource, Boolean))
Filters the elements of an observable sequence based on a predicate.
Namespace: System.Reactive.Linq
Assembly: System.Reactive (in System.Reactive.dll)
static member Where : source:IObservable<'TSource> * predicate:Func<'TSource, bool> -> IObservable<'TSource>
Type Parameters
- TSource
The type source.
Parameters
- source
- Type: System.IObservable(TSource)
An observable sequence whose elements to filter.
- predicate
- Type: System.Func(TSource, Boolean)
A function to test each source element for a condition.
Return Value
Type: System.IObservable(TSource)An observable sequence that contains elements from the input sequence that satisfy the condition.
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 http://msdn.microsoft.com/en-us/library/bb384936(v=vs.103).aspx or http://msdn.microsoft.com/en-us/library/bb383977(v=vs.103).aspx.The following example uses the Where operator with a Language Integerated Query (LINQ) to filter the integer sequence so that only even integers are produced for the sequence.
using System;
using System.Reactive.Linq;
namespace Example
{
class Program
{
static void Main()
{
//*********************************************************************************************//
//*** The mainSequence produces a new long integer from the Interval operator every sec. ***//
//*********************************************************************************************//
var mainSequence = Observable.Interval(TimeSpan.FromSeconds(1));
//*********************************************************************************************//
//*** This LINQ statement uses the Where operator to filter the integers in the sequence so ***//
//*** that only the even integers are returned. ***//
//*** ***//
//*** you could also call the method explicitly. For example... ***//
//*** ***//
//*** var seqWhereEven = mainSequence.Where(x => x % 2 == 0); ***//
//*** ***//
//*********************************************************************************************//
var seqWhereEven = from i in mainSequence
where i % 2 == 0
select i;
//*********************************************************************************************//
//*** Create a subscription and write each of the even integers to the console window. ***//
//*********************************************************************************************//
seqWhereEven.Subscribe(x => Console.WriteLine(x));
Console.ReadLine();
}
}
}
The following output was generated by the example code.
0 2 4 6 8 10 12 14 16