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;
}
}
CodePudding user response:
I think you are looking for this if I understand correctly:
if (items.Any(t => t.ToLower() == abc && 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.
CodePudding user response:
You can compare twice: case insensitive and case sensitive:
if (items.Any(item => abc.Equals(item, StringComparison.OrdinalIgnoreCase) &&
abc.Equals(item, StringComparison.Ordinal)))
{
Console.WriteLine("matched");
}