How do I get the case insensitive match in List<string>?
.net-4.0, c#
Solution
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.
Problem
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.