Kurkula Kurkula - 1 month ago 9
C# Question

csharp string comparision error

I am trying to check if value exists in a string array. The below one works but when I tried the next code block,it failed.

bool exixts;
string toCheck= "jupiter";
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains(toCheck))
{
exists = true;
}


How can I check for trim and casesensitivity

I tried this

bool exixts;
string toCheck= "jupiter ";
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains(toCheck.Trim(),StringComparison.InvariantCultureIgnoreCase)))
{
exists = true;
}

Answer

Or you can do like this,

bool exists = printer.Any(x=> x == toCheck.Trim());

Hope helps,