Living. Dreaming. Coding
Making string dictionary key case insensitive

Making string dictionary key case insensitive

A colleague pointed me to a cool way to make dictionary searches case insensitive. So I thought it’d share it with you guys.

Well the way to do it is like this:

void Main()
{
  var dictionary = new CaseInsensitiveKeyDictionary<string>();
  dictionary.Add("a", "Value 1");
  dictionary.Add("b", "Value 2");
  dictionary.Add("c", "Value 3");
  
  Console.WriteLine(dictionary["A"]); //Will display Value 1
}


public class CaseInsensitiveKeyDictionary<T> : Dictionary<string,T>
{
  public CaseInsensitiveKeyDictionary() : base(StringComparer.InvariantCultureIgnoreCase)
  {
  }
}

This is like cool for specific use case but you can also pass other IEQualityComparers here. More info can be found here

Leave a Reply

Your email address will not be published.