0

I have some values from MySQL . and I want to know ... how I can do the following :

if (Value.ToString() == "1" || Value.ToString() == "2" || Value.ToString() == "3" && SecondValue.ToString() == "5")

Value can be : 1 "or" 2 "or" 3 ... and Second Value "5" . means One of (the three "Value") && SecondValue . or there is no way to do that ? and I should just do this :

if (Value.ToString() == "1" && SecondValue.ToString() == "5"
{
}
if (Value.ToString() == "2" && SecondValue.ToString() == "5"
{
}
ect ....

Thank you for your answer .

4

6 回答 6

8

Your code is almost correct but you need to add an extra parenthesis around the "or" conditions to group them.

if ((Value.ToString() == "1" || Value.ToString() == "2" || Value.ToString() == "3") 
 && SecondValue.ToString() == "5")
于 2013-10-17T17:56:39.773 回答
2

I think what you're trying to go for is this:

 if (new List<string>() { "1", "2", "3" }.Contains(Value.ToString()) && SecondValue.ToString() == "5")
于 2013-10-17T17:57:15.947 回答
1

Try this, it is clean enugh:

if (SecondValue.ToString() == "5")
{
   if (Value.ToString() == "1" || Value.ToString() == "2"  || Value.ToString() == "3")
   {
      //Do Stuff
   }
}

Regards, Krekkon

于 2013-10-17T17:57:59.090 回答
1

You can use parenthesis to group your boolean conditions however you want. If you want a case where "one of these cases is true and also one of these other cases is true", group the cases appropriately. In your case, you'd be better off using a collection to hold your values for valid cases for "Value", something like:

var myValue = Value.ToString();
var myValidCases = new [] {"1", "2", "3"};
if(myValidCases.Any(validCase => validCase == myValue) && SecondValue.ToString() == "5")
{
  //do something
}
于 2013-10-17T17:58:38.927 回答
0
if 
(
    (
        Value.ToString() == "1" || 
        Value.ToString() == "2" || 
        Value.ToString() == "3"
    ) && 
    SecondValue.ToString() == "5"
)
于 2013-10-17T17:56:30.290 回答
0

Here's what it looks like basically:

(Value == 1 && SecondValue == 5) || (Value == 2 && SecondValue == 5) || (Value == 3 && SecondValue == 5)

Now the && operator is very much like the multiplication operator in that it is distributive. Which means we can do this:

(Value == 1 || Value == 2 || Value == 3) && SecondValue == 5
于 2013-10-17T17:57:01.887 回答