c# - 检查列表是否包含具有不同大小写的相同字符串
问题描述
我正在尝试提供一个查询,该查询告诉我天气是否字符串列表仅在大小写不同的情况下与输入匹配。请帮忙。
如果输入是“动物”,那么我需要得到一个真实的。如果输入是“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;
}
}
解决方案
您可以比较两次:区分大小写和区分大小写:
if (items.Any(item => abc.Equals(item, StringComparison.OrdinalIgnoreCase) &&
abc.Equals(item, StringComparison.Ordinal)))
{
Console.WriteLine("matched");
}
推荐阅读
- vue.js - Vue:使用新的图像/转换指令预加载图像到 Methode
- python - 当指针打开和指针关闭时,Tkinter 需要一个按钮来更改背景颜色
- flutter - 网络调用后如何修改 UI 以填充子小部件
- python - python中的分组列表
- git - 无法通过 git pull 拉取代码
- java - 当我使用 webflux 和 hatoas 时不显示绝对路径
- javascript - 如何循环消息收集器?
- php - 在 Laravel 中使用不同的外键创建变形关系
- json - Amazon ECS 容器运行状况检查
- django - StreamingHttpResponse 不适用于 ASGI,但可以正常使用 WSGI