【发布时间】:2021-12-17 06:26:06
【问题描述】:
我正在尝试提供一个查询,该查询告诉我天气是否字符串列表仅在大小写不同的情况下与输入匹配。请帮忙。
如果输入是“动物”,那么我需要得到一个真实的。如果输入是“Animal”,那么我应该得到一个错误,因为输入与项目列表中的大小写完全匹配。我不能说 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;
}
}
【问题讨论】:
-
IndexOf和0比较是个坏主意也是 因为如果source是"Animalissimo"并且toCheck是"animal",那么索引返回的是0,因为有一个子字符串最初从source开始。