[英]Check if a list contains the same string with different case
我試圖提供一個查詢,如果字符串列表與輸入匹配,則僅在大小寫不同時告訴我天氣。 請幫忙。
如果輸入是“動物”,那么我需要得到一個真實的。 如果輸入是“動物”,那么我應該得到一個錯誤,因為輸入與項目列表中的大小寫完全匹配。 我不能說 StringComparison.OrdinalIgnoreCase 因為它總是返回 true 。
class Program
{
static void Main(string[] args)
{
string abc = "animal";
List<string> items = new List<string>() { "Animal", "Ball" };
if (items.Any(x => x.Matches(abc, StringComparison.Ordinal)))
{
Console.WriteLine("matched");
}
Console.ReadLine();
}
}
static class Extentions
{
public static bool Matches(this string source, string toCheck, StringComparison comp)
{
return source?.IndexOf(toCheck, comp) == 0;
}
}
在敏感和大小寫敏感的情況下:您可以比較兩次:
if (items.Any(item => abc.Equals(item, StringComparison.OrdinalIgnoreCase) &&
abc.Equals(item, StringComparison.Ordinal)))
{
Console.WriteLine("matched");
}
如果我理解正確,我認為您正在尋找這個:
if (items.Any(t => abc.Equals(t, StringComparison.OrdinalIgnoreCase) &&
t != abc))
{
Console.WriteLine("matched");
}
if 的第一部分將匹配字符串以檢查第二部分將確保它們不是相同的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.