在不区分大小写字典键忽略连字符 [英] Ignoring hyphen in case insensitive dictionary keys
本文介绍了在不区分大小写字典键忽略连字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在asp.net/vb.net这样一个区分大小写的字典:
I have a case insensitive dictionary in asp.net/vb.net like this:
Dim caseInsensitiveDictionary = New Dictionary(Of String, Single)(StringComparer.OrdinalIgnoreCase)
它拥有这样的价值观
it holds values like this
one hundred, 100
one hundred one, 101
one hundred two, 102
我想,如果用户试图找到这样一个值:
I want that if a user tries to find a value like this:
Response.Write(dictionary("ONE-hundred").ToString)
他得到100,但现在它是因为字典键不必hyphon变得异常 - 。哪一种方法做我需要重写。
he gets 100 but right now it gets exception because dictionary keys don't have hyphon '-'. Which method do i need to override.
请提示
推荐答案
您既可以添加一百,100
以及到字典中(最简单的方法)或建立一个自定义 StringComparer
:
You could either add ONE-hundred,100
as well to the dictionary(the easiest approach) or build a custom 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")
这篇关于在不区分大小写字典键忽略连字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文