[Solved] Compare two strings to a value in C# [closed]


I’d advise against using == to test string equality. Use String.Equals() instead.

You can also do this in one statement using Linq:

if ((new [] {string1, string2, ...}).Any(s=>string.equals(s,"No",StringComparison.CurrentCultureIgnoreCase)))
{
 DoStuff();
}

This will DoStuff() if any of your strings are equal to “no” ignoring the case.

See String.Equals() and Enumerable.Any() for further reading. It should be noted that an Enumerable is any class that can be enumerated, so this includes almost all collections like arrays and lists.

Replace string1,string2,... with all of your string variable names. I’d also advise changing your report card class to have a List<string> of results (assuming all of your results are strings) rather than these fields. That way you could enumerate over it like a collection.

See List<T>.

You also can’t have variable names that start with strings.


If you absolutely HAVE to use ORs, you need to perform each comparison separately and then chain them together. The way you’ve done it essentially reads “if string1 or string2 or string3 or string4 equals “no””. Which will evaluate as though you’re saying ((string1 or string2) or (string3 or string4)) equals “no”.

Obviously, “apple or pair” isn’t a valid operation. So what you want is “string1 equals “no” or string2 equals “no” or string3 equals “no”…

To do this in C# you’d use something like:

if (string1 == "No" ||
    string2 == "No" ||
    stringN == "No" ||)
{
   DoStuff();
}

I’d strongly advise against using this approach though as it’s poor practice. Even if it’s beyond the scope of your assignment, read up on the links I’ve posted and try and implement it in a more robust fashion. If this is a school assignment, most teachers will be happy to see a “better” solution than the one they’re looking for. Just don’t copy and paste the code I’ve provided and make sure you understand it.

5

solved Compare two strings to a value in C# [closed]