Case-insensitive Dictionary in C#


To compare, ignoring case, use the case-insensitive Dictionary.

While declaring a Dictionary, set the following property to get case-insensitive Dictionary −

StringComparer.OrdinalIgnoreCase

Add the property like this −

Dictionary <string, int> dict = new Dictionary <string, int> (StringComparer.OrdinalIgnoreCase);

Here is the complete code −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Program {
   public static void Main() {
      Dictionary <string, int> dict = new Dictionary <string, int>       (StringComparer.OrdinalIgnoreCase);
      dict.Add("cricket", 1);
      dict.Add("football", 2);
      foreach (var val in dict) {
         Console.WriteLine(val.ToString());
      }
      // case insensitive dictionary i.e. "cricket" is equal to "CRICKET"
      Console.WriteLine(dict["cricket"]);
      Console.WriteLine(dict["CRICKET"]);
   }
}

Output

[cricket, 1]
[football, 2]
1
1

Updated on: 22-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements