l33t
l33t

Reputation: 19976

Flatten collection of collections using CompositeCollection?

I have an ObservableCollection with a number of MyParent objects, that in turn have their own ObservableCollection of MyChild objects. Now I want to show all MyChild objects in a grid view, which naturally asks for a flattened collection.

CompositeCollection looks promising.

Q: Is it possible to wrap an arbitrary number of collections in a CompositeCollection?

If not, are there alternatives?

Upvotes: 0

Views: 342

Answers (2)

CodingNinja
CodingNinja

Reputation: 81

You can write a converter like this:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var parent = value as IEnumerable<Parent>;

    // Note: CompositeCollectionView not support grouping。
    var compositeCollection = new CompositeCollection();

    foreach (var child in parent)
    {
        var collectionContainer = new CollectionContainer {
            Collection = child.SomeCollectionProperty;
        };

        compositeCollection.Add(collectionContainer);
    }

    return compositeCollection;
}

Upvotes: 1

Sheridan
Sheridan

Reputation: 69987

There's no need to use any CompositeCollection to do what you want. You can extract all of the MyChild objects from all of the MyParent objects using the Enumerable.SelectMany Method in a simple LinQ query. Try this:

using System.Linq;

...

var children = YourParentCollection.SelectMany(i => i.MyChild).ToList();

If you're not familiar with these Enumerable extension methods, you should definitely investigate them.

Upvotes: 2

Related Questions