How to get case insensitive 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 the word I specify is listed, how do I get case-sensitive spelling of a word from the list? For example, .Contains () is true when the word "sodium phosphate" is used, but the list contains "sodium phosphate." How can I do case-insensitive searches ("sodium phosphate") but return case-sensitive searches ("sodium phosphate") from the list?
I prefer to avoid a dictionary in which the key is uppercase and the value is correctly circled or vice versa.
You need something like:
string match = list.FirstOrDefault(element => element.Equals(target, StringComparison.CurrentCultureIgnoreCase)); This will cause match be used as a null reference if no match is found.
(You can use List<T>.Find , but with FirstOrDefault code becomes more general, since it will work - using System.Linq; at the top of the file) in any sequence of lines.)
Please note that I am assuming there are no null items in the list. If you want to handle this, you can use the static method call instead: string.Equals(element, target, StringComparison.CurrentCultureIgnoreCase) .
Also note that I assume you want to compare with the culture. See StringComparison for other parameters.
Consider if a case insensitive dictionary is comparable for you. If you don't care about Dictionary word order, you'll get much better search performance than a list.
Dictionary<string, string> openWith = new Dictionary<string, string>( StringComparer.CurrentCultureIgnoreCase);