-2

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 case sensitivity?

I tried this

bool exixts;
string toCheck= "jupiter   ";

string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
 if(printer.Contains(toCheck.Trim(),StringComparison.InvariantCultureIgnoreCase)))
{
    exists = true;
}
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
Kurkula
  • 6,945
  • 26
  • 108
  • 186

2 Answers2

2

The IEnumerable<string>.Contains(value, comparer) expects a compare class instance, not an enum value.

The library does have some ready made comparers available though:

//if(printer.Contains(toCheck.Trim(),StringComparison.InvariantCultureIgnoreCase)))
if (printer.Contains(toCheck.Trim(), StringComparer.OrdinalIgnoreCase)) 
Henk Holterman
  • 250,905
  • 30
  • 306
  • 490
1

Or you can do like this,

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

Hope helps,

Berkay Yaylacı
  • 4,293
  • 2
  • 18
  • 34