String Comparison by Ignoring Case in C#

How to compare two string values while ignoring case sensitivity in C#

String value in C# is case-sensitive. That means lower case and upper case texts are considered different when you compare them.

But, there are some cases when you need to compare two strings and ignore their case. For example when you’re building a search engine.

To compare two strings by ignoring their case, you can just put an additional parameter when you’re using string.Equals() method.

Take a look the following snippet as an example.

var string1 = "this is a string";
var string2 = "This Is A String";
var isSame = string.Equals(string1, string2,  StringComparison.OrdinalIgnoreCase);

// Output:
//  isSame = true

Using String as Dictionary Key by Ignoring Case

When you’re using a Dictionary collection, you can also use string value as the Key. But, by default Dictionary will compare two strings as different if the case doesn’t match. You can change this behaviour by setting a parameter when you initialize a Dictionary.

Check following snippet for an example how to initialize a Dictionary by using string as the Key but ignoring its case when you try to access a value from a Key.

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

dict.Add("key", "value");

var getValue = dict["KEY"];

// Output:
//  getValue = "value"