How to ignore the case sensitivity in List<string>
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,
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));
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));
您可以通过提供不区分大小写的字符串相等比较器来使用Contains
,如下所示:
if (myList.Contains(keyword, StringComparer.OrdinalIgnoreCase))
{
Console.WriteLine("Keyword Exists");
}
链接地址: http://www.djcxy.com/p/75192.html
上一篇: 我如何测量2个字符串之间的相似度?