DenaliHardtail
DenaliHardtail

Reputation: 28306

How do I get the case insensitive match in List<string>?

I have a list of words in a List. Using .Contains(), I can determine if a word is in the list. If a word I specify is in the list, how do I get the case sensitive spelling of the word from the list? For example, .Contains() is true when the word is "sodium phosphate" but the list contains "Sodium Phosphate". How do I perform a case-insensitive search ("sodium phosphate") yet return the case-sensitive match ("Sodium Phosphate") from the list?

I prefer to avoid a dictionary where the key is uppercase and the value is proper cased, or vice verse.

Upvotes: 8

Views: 10267

Answers (3)

Akshay G
Akshay G

Reputation: 2280

You can also use StringComparer in list

if (listOfValues.Contains(value, StringComparer.OrdinalIgnoreCase))

Upvotes: 0

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

Consider if Dictionary with case insensitive comparison work for you. Unless you care about order of words Dictionary will give you much better performance of look up than list.

Dictionary<string, string> openWith = 
      new Dictionary<string, string>( 
         StringComparer.CurrentCultureIgnoreCase);

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500425

You want something like:

string match = list.FirstOrDefault(element => element.Equals(target, 
                                     StringComparison.CurrentCultureIgnoreCase));

This will leave match as a null reference if no match can be found.

(You could use List<T>.Find, but using FirstOrDefault makes the code more general, as it will work - with a using System.Linq; directive at the top of the file) on any sequence of strings.)

Note that I'm assuming there are no null elements in the list. If you want to handle that, you may want to use a static method call instead: string.Equals(element, target, StringComparison.CurrentCultureIgnoreCase).

Also note that I'm assuming you want a culture-sensitive comparison. See StringComparison for other options.

Upvotes: 17

Related Questions