/
FlattenNestedObservableCollection.cs
55 lines (46 loc) · 1.57 KB
/
FlattenNestedObservableCollection.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace DynamicData.Snippets.Transform
{
public class FlattenNestedObservableCollection: IDisposable
{
public IObservableCache<NestedChild, string> Children { get; }
public FlattenNestedObservableCollection(IObservableCache<ClassWithNestedObservableCollection, int> source)
{
/*
* Create a flat cache based on a nested observable collection.
*
* Since a new changeset is produced each time a parent is added, I recommend applying Batch()
* after TransformMany() to reduce notifications (particularly on initial load)
*/
Children = source.Connect()
.TransformMany(parent => parent.Children, c=>c.Name)
.AsObservableCache();
}
public void Dispose()
{
Children.Dispose();
}
}
public class ClassWithNestedObservableCollection
{
public int Id { get; }
public ObservableCollection<NestedChild> Children { get; }
public ClassWithNestedObservableCollection(int id, IEnumerable<NestedChild> animals)
{
Id = id;
Children = new ObservableCollection<NestedChild>(animals);
}
}
public class NestedChild
{
public string Name { get; }
public string Value { get; }
public NestedChild(string name, string value)
{
Name = name;
Value = value;
}
}
}