Bidirecional dictionary WITH CASE-INSENSITIVENESS?
Question: I use the bidirectional dicionary class I found here: Bidirectional 1 to 1 Dictionary in C#
The problem is, I need this - case insensitive (StringComparer.OrdinalIgnoreCase)
I wanna extend it to cover the IEqualityComparer constructor. I've converted it to VB (works like a charm), but I have trouble implementing the comparer 'transfer'.
The problem is, in the parameters I have:
ByVal x As System.Collections.Generic.IEqualityComparer(Of TKey)
But the dicionary secondToFirst is of type TValue, TKey, which kills my IEqualityComparer, which needs to be of type TValue instead of TKey...
How do I typecast this comparer ?
If somewhere there's another class for BiDictionaryOneToOne, with case-insensitiveness, that's also OK (开发者_开发百科as long as that library isn't monumental in size/memory consumption and .NET 2.0)
Public Class BiDictionaryOneToOne(Of TKey, TValue)
Public Sub New(ByVal x As System.Collections.Generic.IEqualityComparer(Of TKey))
Dim y As System.Collections.Generic.IEqualityComparer(Of TValue) = StringComparer.OrdinalIgnoreCase
firstToSecond = New Dictionary(Of TKey, TValue)(x)
secondToFirst = New Dictionary(Of TValue, TKey)(y)
End Sub
Edit:
OK, of course it's only possible if TKey & TValue are of type string, as John points out, but in case they are the same, it's still possible with try/catch like this:Public Sub New(ByVal cmpFirstDirection As System.Collections.Generic.IEqualityComparer(Of TKey))
Try
Dim cmpOppositeDirection As System.Collections.Generic.IEqualityComparer(Of TValue) = CType(cmpFirstDirection, System.Collections.Generic.IEqualityComparer(Of TValue))
firstToSecond = New Dictionary(Of TKey, TValue)(cmpFirstDirection)
secondToFirst = New Dictionary(Of TValue, TKey)(cmpOppositeDirection)
Catch ex As Exception
firstToSecond = New Dictionary(Of TKey, TValue)(cmpFirstDirection)
secondToFirst = New Dictionary(Of TValue, TKey)
End Try
End Sub
Public Sub New(ByVal cmpFirstDirection As System.Collections.Generic.IEqualityComparer(Of TKey), ByVal cmpOppositeDirection As System.Collections.Generic.IEqualityComparer(Of TValue))
firstToSecond = New Dictionary(Of TKey, TValue)(cmpFirstDirection)
secondToFirst = New Dictionary(Of TValue, TKey)(cmpOppositeDirection)
End Sub
You're trying to write a generic bi-dictionary which could have any key/value pair combination of types. What does it mean to compare two integers using StringComparer
? I suggest you change your constructor to take two IEqualityComparer
s, one for TKey
and one for TValue
. You can then create a BiDictionaryOneToOne(Of String, String)
which is case-insensitive by passing in two appropriate IEqualityComparer(Of String)
values.
精彩评论