How can I make Array.Contains case-insensitive on a string array?

.Net

.Net Problem Overview


I am using the Array.Contains method on a string array. How can I make that case-insensitive?

.Net Solutions


Solution 1 - .Net

array.Contains("str", StringComparer.OrdinalIgnoreCase);

Or depending on the specific circumstance, you might prefer:

array.Contains("str", StringComparer.CurrentCultureIgnoreCase);
array.Contains("str", StringComparer.InvariantCultureIgnoreCase);

Solution 2 - .Net

Some important notes from my side, or at least putting some distributed info at one place- concerning the tip above with a StringComparer like in:

if (array.Contains("str", StringComparer.OrdinalIgnoreCase))
{}
  1. array.Contains() is a LINQ extension method and therefore works by standard only with .NET 3.5 or higher, needing:
    using System;
    using System.Linq;

  2. But: in .NET 2.0 the simple Contains() method (without taking case insensitivity into account) is at least possible like this, with a cast:

    if ( ((IList<string>)mydotNet2Array).Contains(“str”) ) {}

As the Contains() method is part of the IList interface, this works not only with arrays, but also with lists, etc.

Solution 3 - .Net

Implement a custom IEqualityComparer that takes case-insensitivity into account.

Additionally, check this out. So then (in theory) all you'd have to do is:

myArray.Contains("abc", ProjectionEqualityComparer<string>.Create(a => a.ToLower()))

Solution 4 - .Net

new[] { "ABC" }.Select(e => e.ToLower()).Contains("abc") // returns true

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike ColeView Question on Stackoverflow
Solution 1 - .NetmmxView Answer on Stackoverflow
Solution 2 - .NetPhilmView Answer on Stackoverflow
Solution 3 - .NetKonView Answer on Stackoverflow
Solution 4 - .NetDarin DimitrovView Answer on Stackoverflow