I have a List
where T
is a class that exposes a \"Username\" property. Username is of a custom type that encapsulates a string. I implemen
In my case, I added a try/catch block inside the Compare function, and displayed the exception Message to the console. If there is a bug inside your compare function, you will get this secondary exception ("Failed to compare two elements...").
My problem was specifically with indexing to position 3 of a string that was "" due to another bug.
your answer isn't strictly correct from what I can tell. My objects don't implement IComarable or IComparable at all and they still work fine. I am creating a CollectionViewSource and adding sort descriptions just like you and not getting this error. I was getting the error because the property in the sort description was blank. Once I fixed this everything worked fine without the interface. I suspect maybe you had a property incorrect and it drops back to using IComparable if it can't access the property.
Stupidstupidstupid: The custom type has to implement IComparable
as well as IComparable<T>
It seems the SortDescription uses the old fashioned non-generic version of CompareTo
I am going to get some much needed sleep...
As you said, you need to implement the non-generic IComparable
. You can use the Comparer<T> class if you want to implement this interface in a nice generic way :)
In my case, the property being sorted on was object
, and the error was occurring when some of the objects were int
s and others were string
s.
I could've implemented IComparable
, but the usage of the class was really more string geared - I was able to change object
to string
, and make sure that all setters using numbers called .ToString()
, and it was all set from there.