简体   繁体   中英

C# && , || Operators

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 .

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")

我认为您要尝试的是:

 if (new List<string>() { "1", "2", "3" }.Contains(Value.ToString()) && SecondValue.ToString() == "5")

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
}
if 
(
    (
        Value.ToString() == "1" || 
        Value.ToString() == "2" || 
        Value.ToString() == "3"
    ) && 
    SecondValue.ToString() == "5"
)

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

Try this, it is clean enugh:

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

Regards, Krekkon

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM