Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring case in Dictionary keys

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 ?

like image 220
Luciano Avatar asked Sep 18 '12 23:09

Luciano


People also ask

Are Keys in dictionary case sensitive?

Dictionaries are case-sensitive by default - you don't need to do anything.

Is contains key case sensitive?

Remarks. The key is handled in a case-insensitive manner; it is translated to lowercase before it is used.

Is Python get case sensitive?

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.


2 Answers

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());
like image 175
Hiệp Lê Avatar answered Oct 19 '22 02:10

Hiệp Lê


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.

like image 27
Luciano Avatar answered Oct 19 '22 04:10

Luciano