Check for key in pre-existing dictionary in case insensitive manner

1.3k Views Asked by At

I want to check if a dictionary given to me contains a particular string as a key. I need to make this check in a case insensitive manner. For example if someone passes me a HTTP request object which has a dictionary of strings called headers. I need to be able to check if "Content-Type" or "content-type" or "content-Type" is a key in the request.headers dictionary.

The usual ContainsKey() does not work since I think it checks for the key in a case sensitive manner.

I also know that there exist ways to work on this by defining the dictionary to be case insensitive. But here I do not have control over what kind of dictionary is passed to me.

1

There are 1 best solutions below

0
On

You have two options avaliable to you, since you don't have control over how the dictionary is constructed:

iterate the entire dictionary's pairs to find the given key:

var match = dictionary.Where(pair => string.Equals(pair.Key, "hello"
    , StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

Or to create a new dictionary with your own comparer:

var caseSensitiveDictionary = new Dictionary<string, string>(dictionary
    , StringComparer.InvariantCultureIgnoreCase);

The given comparer is going to be used in creating the hashes for the keys that are added, so if the dictionary is constructed with some other comparer then the hash of a given string using that comparer won't match the non-case-sensitive comparer, so it can't help you.

If you're only going to be checking the dictionary once you're better off just iterating through the keys. If you are going to be performing more than one search at a time then using a newly constructed dictionary is very possibly worthwhile.