Difference between String.Sort and Greater Than/Less Than Operators VB.Net
I have a simple routine to find the next object based on a name property in an un-ordered collection of objects. I go through the collection and collect all the names in a List(of String)
adding any names that are >
my current name, which should give a list of everything that comes after the current key. I then sort the list using the default .Sort()
method on the List(of String)
and take the first item in the list, which should be my next item. I do the reverse to find the previous item, add all items <
my current name, sort, and take the last item in the list.
However, this method skips over some items. For ex开发者_开发百科ample I have items named 1210, 1210-ADA, and 1210_ADA_DB. Using this method, getting the next item skips the middle item 1210-ADA and finds 1210_ADA_DB, but finding the previous item seems to work.
If my process is correct, my only explanation is that the <
and >
operators compare differently than the .Sort()
method. Is this true? What are the differences?
Code for finding next item:
Dim Key As String = Name
Dim NameList As New List(Of String)
For Each obj As T In Collection
Dim ObjKey As String = Obj.Key
If ObjKey > Key Then
NameList.Add(ObjKey)
End If
Next
If NameList.Count = 0 Then Return Nothing
NameList.Sort()
Dim NextKey As String = NameList.First
I think you already found what the problem might be. But to annotate, you are getting bitten by some VB6 compat behavior. The default for Option Compare is Binary which uses String.CompareOrdinal(). Not what List.Sort() uses. Option Compare Text uses CultureInfo.CompareInfo.Compare() with the CompareOptions.IgnoreWidth, CompareOptions.IgnoreKanaType, CompareOptions.IgnoreCase options. Also not what List.Sort() uses.
Avoid the operators and use String.Compare() instead.
my only explanation is that the < and > operators compare differently than the .Sort() method. Is this true?
No. Sort
internally uses the String.IComparable(Of String).CompareTo
method which yields results consistent with <
and >
.
However, this is only true as long as you have not changed the Option Compare
for the project or the current file. This will change the behaviour of <
and >
but not of the above-mentioned method.
精彩评论