C# Array.Contains() – Incase Sensitive Search – Ignore Case

  • by
C#-Array-Contains-Incase-Sensitive-Search-Ignore-Case

By default Array.Contains function in C# is case sensitive. Most of the times this may create some bugs and errors in your program. The solution to this:

  1. Use StringComparer while using Array.Contains function
  2. Add all your objects in the array to Lower or Upper case and check with stored case.

In the following case we will explore both the possibilities in C# with an example.

Using StringComparer while using Array.Contains function:

C# function example:

public void CheckIngredient()
{
try
{
string ingredient = "OniON";
string[] pizza = { "flour", "tomato", "ketchup", "onion", "garlic", "backing powder", "sugar", "cheese", "mushrooms", "capsicum", "mozzarella", "water" };

if (pizza.Contains(ingredient, StringComparer.OrdinalIgnoreCase))
Console.WriteLine("Pizza is containing " + ingredient);
else
Console.WriteLine("Pizza do not contain" + ingredient);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

Here we are using StringComparer.OrdinalIgnoreCase because of which the cases in the function will be ignored and this will be true.

Output:

C#-Array-Contains-Incase-Sensitive-Search-Ignore-Case

C#-Array-Contains-Incase-Sensitive-Search-Ignore-Case

Lower or Upper Case way:

C# function example:

public void CheckIngredient()
{
try
{
string ingredient = "OniON";
string[] pizza = { "flour", "tomato", "ketchup", "onion", "garlic", "backing powder", "sugar", "cheese", "mushrooms", "capsicum", "mozzarella", "water" };

if (pizza.Contains(ingredient.ToLower()))
Console.WriteLine("Pizza is containing " + ingredient);
else
Console.WriteLine("Pizza do not contain" + ingredient);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

Output:

C#-Array-Contains-Incase-Sensitive-Search-Ignore-Case

C#-Array-Contains-Incase-Sensitive-Search-Ignore-Case

Here since all the object in our array is in lower case we are checking for the ingredient in lower case format.

Both of this functions work but I would recommend to you to use the first method since most of the times in your application you won’t be knowing if the objects are added in which format. It is possible it is added through a database table or from a API response. So first method would work most of the times.

 


1