wpfcompositecollection

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?


Solution

  • 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.