Search code examples
c#.netidictionary

Convert IDictionary<string, string> keys to lowercase (C#)


I've got a Method that gets a IDictionary as a parameter. Now I want to provide a method that retrieves the value from this dictionary, but it should be case-invariant.

So my solution to this right now was to have a static function that loops through the keys and converts them toLower() like this:

private static IDictionary<ILanguage, IDictionary<string, string>> ConvertKeysToLowerCase(
    IDictionary<ILanguage, IDictionary<string, string>> dictionaries)
{
    IDictionary<ILanguage, IDictionary<string, string>> resultingConvertedDictionaries 
        = new Dictionary<ILanguage, IDictionary<string, string>>();
    foreach(ILanguage keyLanguage in dictionaries.Keys)
    {
        IDictionary<string, string> convertedDictionatry = new Dictionary<string, string>();
        foreach(string key in dictionaries[keyLanguage].Keys)
        {
            convertedDictionatry.Add(key.ToLower(), dictionaries[keyLanguage][key]);
        }
        resultingConvertedDictionaries.Add(keyLanguage, convertedDictionatry);
    }
    return resultingConvertedDictionaries;
}

Now, this is ok, but still it's a pretty huge chunk of code that contradicts my idea of "clean and efficient". Do you know any alternatives to this so that the .ContainsKey() method of the dictionary doesn't differentiate between casing?


Solution

  • Yes - pass the Dictionary constructor StringComparer.OrdinalIgnoreCase (or another case-ignoring comparer, depending on your culture-sensitivity needs).