Case-INsensitive Dictionary with string key-type in C#

后端 未结 5 1943
余生分开走
余生分开走 2020-11-30 23:53

If I have a Dictionary is it possible to make methods like ContainsKey case-insensitive?

This seemed related, but I didn\

5条回答
  •  抹茶落季
    2020-12-01 00:28

    I just ran into the same kind of trouble where I needed a caseINsensitive dictionary in a ASP.NET Core controller.

    I wrote an extension method which does the trick. Maybe this can be helpful for others as well...

    public static IDictionary ConvertToCaseInSensitive(this IDictionary dictionary)
    {
        var resultDictionary = new Dictionary(StringComparer.InvariantCultureIgnoreCase);
        foreach (var (key, value) in dictionary)
        {
            resultDictionary.Add(key, value);
        }
    
        dictionary = resultDictionary;
        return dictionary;
    }
    

    To use the extension method:

    myDictionary.ConvertToCaseInSensitive();
    

    Then get a value from the dictionary with:

    myDictionary.ContainsKey("TheKeyWhichIsNotCaseSensitiveAnymore!");
    

提交回复
热议问题