Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net-4.0

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.

like image 852
DenaliHardtail Avatar asked Mar 11 '13 20:03

DenaliHardtail


People also ask

How do you do a case insensitive search in Python?

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.

How do you make a list not case-sensitive in Python?

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.

Does list contain case-sensitive?

C#: List. Contains Method – Case Insensitive.


1 Answers

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.

like image 167
Jon Skeet Avatar answered Oct 20 '22 20:10

Jon Skeet