Search This Blog

Friday, August 3, 2012

Searching a list<string> with case insensitivity

A lot of my web methods generate a list of strings from different sources that I want to quickly scan using the ".contains()" method.

Unfortunately the default method is case sensitive and, since I get information from different sources with differing casing-methods, my code will miss matches with slightly different casing.

string findMe = "String2Find"; 
List someStrings = new List{"one", "Two", "string2FIND", "Three"}; 
Console.WriteLine someStrings.contains(findMe);
 ==== Console === 
(false)
 ================ 

The bad solution is to go thru the list using .tolower() to lowercase all the members and compare each one against the comparator -- with the advent of LINQ there's a new overload for the method which allows comparisons without regard to case: 

string findMe = "String2Find"; 
List someStrings = new List{"one", "Two", "string2FIND", "Three"}; 
Console.WriteLine someStrings.contains(findMe, StringComparer.OrdinalIgnoreCase); 

==== Console === 
(true) 
================ 

I couldn't find this in the standard MSDN locations but it popped out at https://nickstips.wordpress.com/2010/08/24/c-ignore-case-on-list-contains-method/#comment-801