简体   繁体   中英

Check if a list contains the same string with different case

I am trying to come with a query that tells me weather if a list of string matches the input only if the case is different. Please help.

if the input is "animal" then I need to get a true. If the input is "Animal" then I should get a false because the input matches exactly with the case in the items list. I can't say StringComparison.OrdinalIgnoreCase because it always returns a true then.

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;
        }
    }

You can compare twice: case in sensitive and case sensitive:

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

I think you are looking for this if I understand correctly:

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

The first part of the if will match the string to check the second will make sure they aren't the same case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM