How to make IEnumerable<string>.Contains case-insensitive?

Suppose I have a .net Array of strings.

string[] strings = new string[] { "AbC", "123", "Xyz", "321" };

If I wanted to see if the array of strings contains "ABC", I could write

strings.Contains("ABC");

However, suppose that I want a function that will return true if the uppercase values of the strings contain "ABC". I could uppercase the entire array, but it looks like the .Contains method has some overloads for specifying the comparison, but I'm confused by the syntax.

How can I use the IEnumerable<string>.Contains() method implement this logic?


Solution 1:

Use overloaded Enumerable.Contains method which accepts equality comparer:

strings.Contains("ABC", StringComparer.InvariantCultureIgnoreCase)

Also there is strings comparer in box which you can use.

Solution 2:

I personally like this guy's LambdaComparer, which is really useful for stuff like this:

LINQ Your Collections with IEqualityComparer and Lambda Expressions

Example Usage:

var comparer = new LambdaComparer<string>(
    (lhs, rhs) => lhs.Equals(rhs, StringComparison.InvariantCultureIgnoreCase));

var seq = new[]{"a","b","c","d","e"};

Debug.Assert(seq.Contains("A", comparer));