LIST中的c#不区分大小写的匹配

时间:2012-11-12 20:28:50

标签: c#

我有一个列表如下。

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应与列表中的老虎匹配。

在上面的例子中,“创建老虎”将打印在控制台上。

2 个答案:

答案 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);

指定StringComparerStringComparison将允许您搜索不区分大小写的值。大多数String类方法将提供支持其中一个的重载。

相关问题