Skip to content

Observable collection mapper

Chillersanim edited this page Aug 25, 2019 · 2 revisions

The observable collection mapper is used to get an automatically mapped list from a base list.
For that, a base list and a mapping function needs to be provided.

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

The observable collection mapper is useful, if you need to repeatedly access the mapped items, without wanting to repeatedly map these items.

Usage example
Assuming you had a bunch of numbers and wanted to repeatedly print their length, without using ToString() unnecessary often.
This can be easily achieved by using the observable collection mapper.

var numbers = new ObservableCollection<int>();
var mapping = new ObservableCollectionMapper<int, string>(numbers, n => n.ToString());

numbers.Add(0);
numbers.Add(10);

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

numbers.Add(100);
numbers.Add(1000);

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

// Output:
// 0, 1; 10, 2;
// 0, 1; 10, 2; 100, 3; 1000, 4;

This is a rather simple (and silly) example.
But it should give an understanding of what the observable collection mapper can do.

Limitations
Changes to item properties used in the mapping aren't propagated to the output.
This is not currently supported.