C# Dictionary<string,string>(IEqualityComparer<string>?comparer) constructor example

188 Views Asked by At

I have tried to study the below mentioned constructor example of C# in Microsoft Documentation, however I am not able to understand it:

Dictionary<string,string>(IEqualityComparer<string>?comparer)

Can anyone explain me what can be a good example where we can use this constructor along with some sample code. Thanks in advance...

1

There are 1 best solutions below

0
Guru Stron On

I would say that documentation contains good example for this Dictionary<TKey,TValue> constructor:

The following code example creates a Dictionary<TKey,TValue> with a case-insensitive equality comparer for the current culture. The example adds four elements, some with lower-case keys and some with upper-case keys. The example then attempts to add an element with a key that differs from an existing key only by case, catches the resulting exception, and displays an error message. Finally, the example displays the elements in the dictionary.

Dictionary<string, string> openWith =
    new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);

openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("DIB", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

// Try to add a fifth element with a key that is the same
// except for case; this would be allowed with the default
// comparer.
try
{
    openWith.Add("BMP", "paint.exe");
}
catch (ArgumentException)
{
    Console.WriteLine("\nBMP is already in the dictionary.");
}

// List the contents of the sorted dictionary.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key,
        kvp.Value);
}

i.e. this dictionary performs case-insensitive hashcode calculation and comparison using current culture (for example "bmp", "BMP" and "bMp" will be matched into the same entry in the dictionary).

More concise example can look as simple as:

var caseSensitive = new Dictionary<string, string>();
var caseInsensitive = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
caseSensitive.Add("test", string.Empty);
caseInsensitive.Add("test", string.Empty);
Console.WriteLine(caseSensitive.ContainsKey("test"));    // prints True 
Console.WriteLine(caseSensitive.ContainsKey("TEST"));    // prints False
Console.WriteLine(caseInsensitive.ContainsKey("TEST"));  // prints True
Console.WriteLine(caseInsensitive.ContainsKey("TEST"));  // prints True