I am using the Array.Contains method on a string array. How can I make that case-insensitive?
views:
777answers:
5
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
2009-06-04 19:43:51
A:
new[] { "ABC" }.Select(e => e.ToLower()).Contains("abc") // returns true
Darin Dimitrov
2009-06-04 19:44:04
+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
2009-06-04 19:44:29
Why reinvent the wheel?
Mehrdad Afshari
2009-06-04 19:46:29
Because up until 5 minutes ago I didn't know a StringComparer existed. :)
Kon
2009-06-04 19:51:04
+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
2009-06-04 19:46:15
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
2010-09-23 07:45:17