Culture sensitivity in List<string> – how to do comparison

I recently stumbled upon a small c# problem I thought would have been easy to fix… But even now with the .Net framework 3.5, I can’t find a good solution!

So first the details on the problem. When you are using Generics, it’s very easy to construct lists of strings! Example: List<string> foo = null;
And when you want to search for a specific value inside this string list, you would most likely use the .Contains() method… But this has one huge drawback, it will only use the default equality comparer!
Details can be found in the MSDN information of the .Contains() method on List<T>.

In other words, you can’t search for Culture insensitive stuff, nor can you search for Case insensitive stuff!!
To illustrate, in following example the boolean value of contains will be FALSE, because “test” is not the same as “TEST” based on the case sensitivity of the default equality comparer.


List<string> foo = new List<string>();
foo.Add("test");
bool contains = foo.Contains("TEST");

But thanks to the Exists method on List<T>, we are able to write some extra code that will allow us to check against case insensitive strings.


List<string> foo = new List<string>();
foo.Add("test");
bool containsValue = foo.Exists(delegate(string argument)
{
return argument.Equals("TEST", StringComparison.OrdinalIgnoreCase);
});

In this last example, after the Exists method, the boolean value of containsValue will be TRUE… This because now we use the StringComparer class with the indication that we are not interested in case sensitivity!

The given problem has already been brought up by “Andrew Webb” as an enhancement request for the .Net framework ( cfr. his comment in this BCL Team blog post for .Net 4.0 ) and it seems the BCL team will take a look at it. ( fingers crossed )

[tags]c#, Generics[/tags]

Leave a Reply

Your email address will not be published. Required fields are marked *