Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore the case sensitivity in List<string>

Tags:

c#

Let us say I have this code

string seachKeyword = ""; List<string> sl = new List<string>(); sl.Add("store"); sl.Add("State"); sl.Add("STAMP"); sl.Add("Crawl"); sl.Add("Crow"); List<string> searchResults = sl.FindAll(s => s.Contains(seachKeyword)); 

How can I ignore the letter case in Contains search?

Thanks,

like image 546
Mark Avatar asked Jun 24 '10 06:06

Mark


People also ask

How do you ignore 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.

How do you make a list case-insensitive in Python?

1 Answer. To do a case-insensitive search, you need to convert your target string and strings in the list to either lowercase or uppercase.

How do I find a string without case sensitive?

To compare strings without case sensitivity, fold the values using tolower() or toupper() . Using tolower() or toupper() or the above in either order makes no difference when looking for equality, but can make an order difference.


2 Answers

Use Linq, this adds a new method to .Compare

using System.Linq; using System.Collections.Generic;  List<string> MyList = new List<string>(); MyList.Add(...) if (MyList.Contains(TestString, StringComparer.CurrentCultureIgnoreCase)) {     //found }  

so presumably

using System.Linq; ...  List<string> searchResults = sl.FindAll(s => s.Contains(seachKeyword, StringComparer.CurrentCultureIgnoreCase));   
like image 177
CestLaGalere Avatar answered Sep 17 '22 16:09

CestLaGalere


The best option would be using the ordinal case-insensitive comparison, however the Contains method does not support it.

You can use the following to do this:

sl.FindAll(s => s.IndexOf(searchKeyword, StringComparison.OrdinalIgnoreCase) >= 0); 

It would be better to wrap this in an extension method, such as:

public static bool Contains(this string target, string value, StringComparison comparison) {     return target.IndexOf(value, comparison) >= 0; } 

So you could use:

sl.FindAll(s => s.Contains(searchKeyword, StringComparison.OrdinalIgnoreCase)); 
like image 32
Igal Tabachnik Avatar answered Sep 19 '22 16:09

Igal Tabachnik