How to ignore case in dictionary keys? I'm doing this:
var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
map.Add("e", "Letter e lower case");
string value = null;
if (!map.TryGetValue("E", out value)) {
Console.WriteLine("Not found");
}
And I already tried to use StringComparer.InvariantIgnoreCase, and the result is the same. It cannot find the letter "E" in uppercase.
EDIT: Could I'm having some kind of culture conflicts with my environment settings even using OrdinalIgnoreCase ?
Dictionaries are case-sensitive by default - you don't need to do anything.
Remarks. The key is handled in a case-insensitive manner; it is translated to lowercase before it is used.
A programming language is said to be case sensitive if it distinguishes between uppercase and lowercase letters. Python is a `case sensitive programming language. Variable, functions, modules and package names are written in lowercase by convention. Class names and constants are written in uppercase.
StringComparer.OrdinalIgnoreCase uses an internal call to Window API "nativeCompareOrdinalIgnoreCase" function in System.Globalization.TextInfo; so it is not Invariant Culture. Too bad the function in mscorlib.dll is internal, we can not test it out.
Anyhow, you should use StringComparer.InvariantCultureIgnoreCase instead of the former.
In case it still refuses to work, you can re-implement the IEqualityComparer
public class StringComparerIgnoreCase : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
if (x != null && y != null)
{
return x.ToLowerInvariant() == y.ToLowerInvariant();
}
return false;
}
public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}
Usage:
var map = new Dictionary<string, string>(new StringComparerIgnoreCase());
I tested it in others machines that I have (4 VMs, and 1 real) and discovered that only in my current VM (Win7 x64, us_eng, some portuguese settings, .net 4.5) the problem occurs. In my real machine and others VMs the test works fine, using OrdinalIgnoreCase as well InvariantIgnoreCase.
So, I guess that something very weird is in that environment, but I cannot spend time now to investigate it.
Unfortunately the question was flagged as useless by some guys, which demotivates my interesting to investigate it deeply.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With