Failed to compare two elements in the array

前端 未结 5 2046
滥情空心
滥情空心 2020-12-11 00:01

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

相关标签:
5条回答
  • 2020-12-11 00:11

    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.

    0 讨论(0)
  • 2020-12-11 00:16

    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.

    0 讨论(0)
  • 2020-12-11 00:25

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

    0 讨论(0)
  • 2020-12-11 00:29

    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 :)

    0 讨论(0)
  • 2020-12-11 00:29

    In my case, the property being sorted on was object, and the error was occurring when some of the objects were ints and others were strings.

    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.

    0 讨论(0)
提交回复
热议问题