您也可以添加ONE-hundred,100
到字典(最简单的方法)或构建自定义StringComparer
:
Class CaseInsensitiveIgnoringStringComparer
Inherits StringComparer
Private caseInsentiveComparer As System.StringComparer = StringComparer.OrdinalIgnoreCase
Public Property IgnoreList As IList(Of String) = Nothing
Public Property ReplaceWith As String = " "
Private Function Replace(original As String) As String
If IgnoreList Is Nothing OrElse IgnoreList.Count = 0 Then
Return original
Else
For Each s As String In IgnoreList
original = original.Replace(s, ReplaceWith)
Next
Return original
End If
End Function
Public Overloads Overrides Function Compare(x As String, y As String) As Integer
Return caseInsentiveComparer.Compare(Replace(x), Replace(y))
End Function
Public Overloads Overrides Function Equals(x As String, y As String) As Boolean
Return caseInsentiveComparer.Equals(Replace(x), Replace(y))
End Function
Public Overloads Overrides Function GetHashCode(obj As String) As Integer
Return caseInsentiveComparer.GetHashCode(Replace(obj))
End Function
End Class
测试
Dim comp = New CaseInsensitiveIgnoringStringComparer() With {.IgnoreList = {"-", "+"}, .ReplaceWith = " "}
Dim caseInsensitiveDictionary = New Dictionary(Of String, Single)(comp)
caseInsensitiveDictionary.Add("One hundred", 100)
caseInsensitiveDictionary.Add("One hundred one", 101)
caseInsensitiveDictionary.Add("One hundred two", 102)
' normally following both lines would cause exceptions '
Dim n100 = caseInsensitiveDictionary("ONE-hundred")
n100 = caseInsensitiveDictionary("oNE+Hundred")