开发者

Failed to compare two elements in the array

I have a List<T> where T is a class that exposes a "Username" property. Username is of a custom type that encapsulates a string. I implemented the IComparable<T> interface on this custom type that simply returns

this.encapsulatedString.CompareTo(other.encapsulatedString)

I defined an ICollectionView of the List thus:

AllUsers=CollectionViewSource.GetDefaultView(myList);

I added a Sortdescription:

AllUsers.S开发者_StackOverflowortDescriptions.Add(new SortDescription("Username",ListSortDirection.Ascending));

On this line the code throws the exception stated in the title. I can sort the list by other means without problem. Where is the exception coming from?


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.


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.


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜