我有一个列表如下。
List<string> Animallist = new List<string>();
Animallist.Add("cat");
Animallist.Add("dog");
Animallist.Add("lion and the mouse");
Animallist.Add("created the tiger");
我有一个输入
的文本框“不要责怪上帝创造了TIGER,但感谢他没有给它翅膀”“
我想查看文本框中的哪些单词与列表中的项目匹配,并在控制台上打印列表。搜索必须不区分大小写。即文本框中的TIGER应与列表中的老虎匹配。
在上面的例子中,“创建老虎”将打印在控制台上。
答案 0 :(得分:7)
var animalFound = Animals
.Where(a=> a.Equals(searchAnimal, StringComparison.OrdinalIgnoreCase));
或者,如果您还想搜索单词:
var animalsFound = from a in Animals
from word in a.Split()
where word.Equals(searchAnimal, StringComparison.OrdinalIgnoreCase)
select a;
哦,现在我已经看过你的长文了
string longText = "Do not blame God for having created the TIGER, but thank him for not having given it wings";
string[] words = longText.Split();
var animalsFound = from a in Animals
from word in a.Split()
where words.Contains(word, StringComparer.OrdinalIgnoreCase)
select a;
答案 1 :(得分:4)
var text = "Do not blame God for having created the TIGER, but thank him for not having given it wings";
var matched = Animallist.Where(o => text.Contains(o, StringComparer.CurrentCultureIgnoreCase));
foreach (var animal in matched)
Console.WriteLine(animal);
指定StringComparer
或StringComparison
将允许您搜索不区分大小写的值。大多数String
类方法将提供支持其中一个的重载。