I have an application that use managed dlls. One of those dlls return a generic dictionary:
Dictionary<string, int> MyDictionary;
bool Success = MyDictionary.TryGetValue( MyIndex, out TheValue );
There's no way to specify a
StringComparer at the point where you try to get a value. If you think about it,
"foo".GetHashCode() are totally different so there's no reasonable way you could implement a case-insensitive get on a case-sensitive hash map.
You can, however, create a case-insensitive dictionary in the first place using:-
var caseInsensitiveDictionary = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
Or create a new case-insensitive dictionary with the contents of an existing case-sensitive dictionary (if you're sure there are no case collisions):-
var oldDictionary = ...; var newDictionary = new Dictionary<string, int>(oldDictionary, StringComparer.OrdinalIgnoreCase);
This dictionary then uses the
GetHashCode() implementation on
StringComparer.OrdinalIgnoreCase such that
comparer.GetHashcode("foo") give you the same value.
Alternately, if there are only a few elements in the dictionary, and/or you only need to lookup once or twice, you can treat the original dictionary as an
IEnumerable<KeyValuePair<K,T>> and just iterate over it:-
var myKey = ...; var myDictionary = ...; var item = myDictionary.First( x => String.Equals(x.Key, myKey, StringComparison.OrdinalIgnoreCase)).Value;
This saves you the cost of creating a new data structure, but in return the cost of a lookup is O(n) instead of O(1).