简体   繁体   English

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

[英]c# case insensitive match in a LIST

I have a list which is as follows. 我有一个清单如下。

List<string> Animallist = new List<string>();
Animallist.Add("cat");
Animallist.Add("dog");
Animallist.Add("lion and the mouse");
Animallist.Add("created the tiger");

I have a textbox where I enter 我有一个文本框输入

"Do not blame God for having created the TIGER, but thank him for not having given it wings”" “不要责怪上帝创造了老虎,但感谢他没有给予它翅膀”

I would like to see which word(s) from the textbox matches items in the list and print the list on the console. 我想查看文本框中的哪个单词与列表中的项目匹配,并在控制台上打印该列表。 The search has to be case insensitive. 搜索必须不区分大小写。 ie TIGER in the text box should match tiger in the list. 即,文本框中的TIGER应该与列表中的Tiger相匹配。

in the above example "created the tiger" will be printed on the console. 在上面的示例中,“创建老虎”将被打印在控制台上。

var animalFound = Animals
    .Where(a=> a.Equals(searchAnimal, StringComparison.OrdinalIgnoreCase));

or, if you also want to search the words: 或者,如果您还想搜索以下单词:

var animalsFound = from a in Animals
             from word in a.Split()
             where word.Equals(searchAnimal, StringComparison.OrdinalIgnoreCase)
             select a;

oh, now i've seen your long text 哦,现在我已经看过你的长文本

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;
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. 指定StringComparerStringComparison将允许您搜索不区分大小写的值。 Most String class methods will provide an overload that supports one of them. 大多数String类方法将提供支持其中一个的重载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM