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.
Python String equals case-insensitive check Sometimes we don't care about the case while checking if two strings are equal, we can use casefold() , lower() or upper() functions for case-insensitive equality check.
Approach No 1: Python String lower() Method This is the most popular approach to case-insensitive string comparisons in Python. The lower() method converts all the characters in a string to the lowercase, making it easier to compare two strings.
C#: List. Contains Method – Case Insensitive.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With