views:

1102

answers:

2

For those of you that like puzzles: I had this problem recently and am sure there must be a nicer solution.

Consider :

  • an ObservableCollection of Foo objects called foos.
  • Foo contains a string ID field
  • I have no control over foos
  • foos will be changing

Then:

  • I have another collection called sortLikeThis
  • sortListThis contains strings
  • The strings are the IDs in the order in which the foos are to be shown

Plus:

  • There may be objects in foos with an ID that is not in sortLikeThis. These need to go at the end.
  • Likewise, there may be strings in sortLikeThis that do not appear in foos.

Is there a nice way to bind to and show in wpf the Foo objects in foos in the order defined by IDs in sortLikeThis ?

Thanks, Lee.

+2  A: 

Sounds like a job for a custom observable collection that implements IEnumerable and has a pretty little enumerator (aaah, yield) that handles the logic of the custom sort.

public class SortFoosLolThx : ObservableCollection<Foo> {
public IList<string> SortList {/*...*/}
/*...*/
public override IEnumerator<Foo> GetEnumerator() { /*...*/ yield foo; /*...*/}
}
Will
Hi Will,I'm not sure this solution works:1. I have no control over the ObservableCollection<Foo> **foos** - so in particular, can not turn it into a sortable one.2. What would trigger a call to SortList if the collection was modified?Lee
Lee Oades
+2  A: 

Have you looked at Bindable LINQ? It allows you to define LINQ queries on top of an observable collection, and makes sure that the LINQ query is performed each time the underlying collection is changed. In your case, you could add an Orderby query on top of the collection.

You can pass the Orderby method a delegate to do the comparison. To set this up you would

  1. Prepare by creating a Dictionary mapping each id in sortLikeThis to an ascending int
  2. Within the comparison delegate, lookup in the dictionary the ids of the two foos that are passed for comparison. Do the appropriate thing if an item cannot be found.
Samuel Jack