Christopher Scott Christopher Scott - 7 months ago 68
C# Question

Sorting a composite collection

So WPF doesn't support standard sorting or filtering behavior for views of CompositeCollections, so what would be a best practice for solving this problem.

There are two or more object collections of different types. You want to combine them into a single sortable and filterable collection (withing having to manually implement sort or filter).

One of the approaches I've considered is to create a new object collection with only a few core properties, including the ones that I would want the collection sorted on, and an object instance of each type.

class MyCompositeObject
enum ObjectType;
DateTime CreatedDate;
string SomeAttribute;
myObjectType1 Obj1;
myObjectType2 Obj2;
class MyCompositeObjects : List<MyCompositeObject> { }

And then loop through my two object collections to build the new composite collection. Obviously this is a bit of a brute force method, but it would work. I'd get all the default view sorting and filtering behavior on my new composite object collection, and I'd be able to put a data template on it to display my list items properly depending on which type is actually stored in that composite item.

What suggestions are there for doing this in a more elegant way?


Update: I found a much more elegant solution:

class MyCompositeObject
    DateTime    CreatedDate;
    string      SomeAttribute;
    Object      Obj1;
class MyCompositeObjects : List<MyCompositeObject> { }

I found that due to reflection, the specific type stored in Obj1 is resolved at runtime and the type specific DataTemplate is applied as expected!