4

我在 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,但现在它得到了异常,因为字典键没有连字符“-”。我需要覆盖哪种方法。

请建议

4

2 回答 2

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();
    }
}

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

于 2012-05-31T08:06:20.690 回答
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")
于 2012-05-31T08:16:28.923 回答