Reputation: 28306
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
Reputation: 2280
You can also use StringComparer
in list
if (listOfValues.Contains(value, StringComparer.OrdinalIgnoreCase))
Upvotes: 0
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
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