忽略不区分大小写的字典键中的连字符

时间:2012-05-31 07:57:21

标签: c# asp.net vb.net

我在asp.net/vb.net中有一个不区分大小写的字典,如下所示:

Dim caseInsensitiveDictionary = New Dictionary(Of String, Single)(StringComparer.OrdinalIgnoreCase)

它拥有像这样的值

one hundred, 100
one hundred one, 101
one hundred two, 102

如果用户试图找到这样的值,我希望如此:

Response.Write(dictionary("ONE-hundred").ToString)

他得到100但是现在它变得异常,因为字典键没有hyphon' - '。我需要覆盖哪种方法。

请建议

2 个答案:

答案 0 :(得分:3)

您必须创建自定义IEqualityComparer。

类似的东西:

public class MyEqualityComparer : IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        return FixString(x).Equals(FixString(y), StringComparison.InvariantCultureIgnoreCase);
    }

    private string FixString(string x)
    {
        // replace hyphens
        return x.Replace("-", " ");
    }

    public int GetHashCode(string obj)
    {
        return FixString(obj).GetHashCode();
    }
}

然后在字典中使用该类:     字典x =新字典(new MyEqualityComparer())

答案 1 :(得分:1)

您也可以将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")