How can I call ToLower () for each row in the collection using LINQ?

Here is my request:

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

countryis the string and argument of the method containing the above purpose. CountryNames- a list of lines. How can I call ToLowerfor each of the lines in CountryNamesto get valid matches for this query. Is there a better way to make case insensitive using LINQ?

+3
source share
4 answers

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

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

It also avoids the temporary lines created by the call ToLower.

+7
source

Same:

m_ListOfHandlers.SingleOrDefault(h => h.CountryNames.Exists(cn => cn.ToLower() == country.ToLower()); 
0

.Any :

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

== `.Equals :

countryName.Equals(country, StringComparison.OrdinalIgnoreCase)

0
source

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

0
source

Source: https://habr.com/ru/post/1746193/


All Articles