tags:

views:

777

answers:

5

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

A: 

Are you able to change the case of the strings before putting them into the array? For example, make them all lowercase to start with, and then use make string you pass to Contains lowercase too:

Array.Contains(s.ToLower()).

Mat Ryer
A: 
new[] { "ABC" }.Select(e => e.ToLower()).Contains("abc") // returns true
Darin Dimitrov
+1  A: 

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()))
Kon
Why reinvent the wheel?
Mehrdad Afshari
Because up until 5 minutes ago I didn't know a StringComparer existed. :)
Kon
+16  A: 
array.Contains("str", StringComparer.InvariantCultureIgnoreCase);

Or depending on the specific circumstance, you might prefer:

array.Contains("str", StringComparer.OrdinalIgnoreCase);
array.Contains("str", StringComparer.CurrentCultureIgnoreCase);
Mehrdad Afshari
A: 

Javascript function:

Array.prototype.contains = function (element) { for (var i = 0; i < this.length; i++) { if (this[i].toLowerCase() == element.toLowerCase()) { return true; } } return false; }

krishnaveni
This was a .NET specific question.
Mike C.