首页 > 解决方案 > 检查列表是否包含具有不同大小写的相同字符串

问题描述

我正在尝试提供一个查询,该查询告诉我天气是否字符串列表仅在大小写不同的情况下与输入匹配。请帮忙。

如果输入是“动物”,那么我需要得到一个真实的。如果输入是“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;
        }
    }

标签: c#listlinq

解决方案


您可以比较两次:区分大小写区分大小写:

if (items.Any(item => abc.Equals(item, StringComparison.OrdinalIgnoreCase) && 
                      abc.Equals(item, StringComparison.Ordinal))) 
{
    Console.WriteLine("matched");
}

推荐阅读