-1

我有一个清单,如下所示。

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 匹配。

在上面的例子中,“created the tiger”将打印在控制台上。

4

2 回答 2

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;
于 2012-11-12T20:31:25.273 回答
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);

Specifying StringComparer or StringComparison will allow you to search for values that are case insensitive. Most String class methods will provide an overload that supports one of them.

于 2012-11-12T20:31:52.993 回答