Skip to content

Observable filtered collection

Chillersanim edited this page Aug 25, 2019 · 2 revisions

The observable filtered collection is used to get an automatically filtered list from a base list.
It works gives access to the same items as in the base list, but only those that match the filter.
For that a base list and a filter function needs to be provided.

If the base list implements the INotifyCollectionChanged interface, changes to the base list are automatically propagated.
The observable filter collection can be used like any normal readonly list and implements the INotifyCollectionChanged to inform about changes.

The observable filtered collection is useful, if you need to repeatedly access the filtered items, without wanting to repeatedly do the filtering.

Usage example
Assuming you have a bunch of numbers and want to only print even numbers.
This can be easily achieved by using the observable filtered collection.

var numbers = new ObservableCollection<int>();
var mapping = new ObservableFilteredCollection<int>(numbers, n => n % 2 == 0);

numbers.Add(0);
numbers.Add(1);
numbers.Add(2);

foreach (var text in mapping)
{
    Console.Write($"{text}, ");
}

numbers.Add(5);
numbers.Add(1000);
numbers.Add(1001);

Console.WriteLine();
foreach (var text in mapping)
{
    Console.Write($"{text}, ");
}

// Output:
// 0, 2
// 0, 2, 1000

This is a rather simple example.
But it should give an understanding of what the observable filtered collection can do.