簡體   English   中英

LIST中的C#不區分大小寫的匹配

[英]c# case insensitive match in a LIST

我有一個清單如下。

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

在上面的示例中,“創建老虎”將被打印在控制台上。

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;
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類方法將提供支持其中一個的重載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM