Coder Perfect

In C#, create a case-insensitive dictionary with a string key type.


Is it feasible to implement methods like ContainsKey case-insensitive if I have a DictionaryString,…>?

This seems to be relevant, but I wasn’t sure: Using declarations in c#, you may make the Key case insensitive.

Asked by Mr. Boy

Solution #1

It does have a connection. The solution is to tell the dictionary instance to use a case insensitive string compare method rather than the usual string compare method (which is case sensitive). This is accomplished by use the right constructor:

var dict = new Dictionary<string, YourClass>(

The dictionary’s constructor wants an IEqualityComparer, which informs it how to compare keys.

StringComparer. InvariantCultureIgnoreCase returns an IEqualityComparer object that compares strings without regard for case.

Answered by Konrad Rudolph

Solution #2

var myDic = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
myDic.Add("HeLlo", "hi");

if (myDic.ContainsKey("hello"))

Answered by Steve

Solution #3

There’s a slim chance you’re dealing with a dictionary obtained from a third-party or external dll. Linq is a query language that can be used in a variety of ways.

YourDictionary.Any(i => i.KeyName.ToLower().Contains("yourstring")))

Answered by Kurkula

Solution #4

You can create a wrapper class that inherits from dictionary class if you have no control over the instance creation, such as if your object is desterilized from json.

public class CaseInSensitiveDictionary<TValue> : Dictionary<string, TValue>
    public CaseInSensitiveDictionary() : base(StringComparer.OrdinalIgnoreCase){}

Answered by A.G.

Solution #5

In an ASP.NET Core controller, I wanted a caseINsensitive dictionary, and I just run into the identical problem.

I created an extension method that does the desired result. Perhaps this will also be useful to others…

public static IDictionary<string, TValue> ConvertToCaseInSensitive<TValue>(this IDictionary<string, TValue> dictionary)
    var resultDictionary = new Dictionary<string, TValue>(StringComparer.InvariantCultureIgnoreCase);
    foreach (var (key, value) in dictionary)
        resultDictionary.Add(key, value);

    dictionary = resultDictionary;
    return dictionary;

To utilize the extension method, follow these steps:


Then use the following formula to extract a value from the dictionary:


Answered by Ferry Jongmans

Post is based on