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 .

1
  • I would prevent calling a method more than once if you don't need to. I'm talking about ToString(), in this case it could be harmless, but you'd rather want to buffer it in another variable. Commented Oct 17, 2013 at 18:09

6 Answers 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") 
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

+1 for more versatility but i would change the List for basic Array. I don't need a 12' Truck to transport a microwave.
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

1 Comment

Thanks to all :p first answer was what I needed .I was looking for
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 } 

Comments

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

Comments

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.