-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
  • 732,580
  • 175
  • 1,330
  • 1,459
Kurkula
  • 6,386
  • 27
  • 127
  • 202

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)) 
H H
  • 263,252
  • 30
  • 330
  • 514
1

Or you can do like this,

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

Hope helps,

Berkay Yaylacı
  • 4,383
  • 2
  • 20
  • 37