tags:

views:

76

answers:

4

Here is my query:

m_SelectedHandler = m_ListOfHandlers.SingleOrDefault(h => h.CountryNames.Contains(country.ToLower());

country is a string and an argument to the method containing the assignment above. CountryNames is a list of strings. How can I call ToLower on each of the strings in CountryNames so that I'll get valid matches for this query. Is there a better way to do a case-insensitive compare using LINQ?

A: 

Like so:

m_ListOfHandlers.SingleOrDefault(h => h.CountryNames.Exists(cn => cn.ToLower() == country.ToLower()); 
klausbyskov
Using ToLower for case-insensitive comparison == fail. http://www.moserware.com/2008/02/does-your-code-pass-turkey-test.html
dtb
@dtb, good point, but I just answered the question.
klausbyskov
+6  A: 

Yes, you can specify an IEqualityComparer<T> to the Contains method. For example, you could use StringComparer.CurrentCultureIgnoreCase:

m_SelectedHandler = m_ListOfHandlers.SingleOrDefault(h => h.CountryNames.Contains(country, StringComparer.CurrentCultureIgnoreCase));

This also avoids the temporary strings created by calling ToLower.

Chris Schmich
A: 

You can just use .Any like this:

m_SelectedHandler = m_ListOfHandlers
    .SingleOrDefault(h => h.CountryNames
        .Any(countryName => countryName.ToLower() == country.ToLower()));

or replace == with `.Equals like so:

countryName.Equals(country, StringComparison.OrdinalIgnoreCase)

to do a case-insensitive match

chakrit
A: 

You could do h.CountryNames.Any(x => StringComparer.CurrentCultureIgnoreCase.Equals(x, country)

Stephen Cleary