Reputation: 14703
I am using the Array.Contains
method on a string array. How can I make that case-insensitive?
Upvotes: 231
Views: 113567
Reputation: 988
From a Powershell point of view, I like to keep things easy to read for everyone, so for:
$data = @('Zero','One','Two','Three')
$data -contains 'three'
will do a case insensitive check but
$data -ccontains 'three'
will be case sensitive. Hope that helps.
Upvotes: 0
Reputation: 3674
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))
{}
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;
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.
Upvotes: 14
Reputation: 421968
array.Contains("str", StringComparer.OrdinalIgnoreCase);
Or depending on the specific circumstance, you might prefer:
array.Contains("str", StringComparer.CurrentCultureIgnoreCase);
array.Contains("str", StringComparer.InvariantCultureIgnoreCase);
Upvotes: 401
Reputation: 27431
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()))
Upvotes: 0
Reputation: 1038710
new[] { "ABC" }.Select(e => e.ToLower()).Contains("abc") // returns true
Upvotes: 0