Compare multiple values ​​in one condition

Int32 int1, int2, int3 = 123; 

Given the variables above, how can I verify that all my variables are 123 without creating a collection to execute some Any or something else?

What i tried

 if(int1 == int2 == int3 == 123) { // Fantastic code here } 

EDIT

I have to apologize, I was not clear enough in my question. I am fully aware of the && operator that I asked regarding "elegance", that is, how can I avoid repeating the value that I want to compare.

In the same way, I assigned all 3 integer variables the same value in one hit, I would like to make a comparison. It seems that this has not yet been done. I think I ask for the impossible, I will have to adhere to the basic syntax and keep it simple.

+7
variables c # conditional if-statement
source share
4 answers

You can create a useful extension function:

 public static bool EqualsAll<T>(this T val, params T[] values) { return values.All(v => v.Equals(val)); } 

name it like this:

 bool res = 123.EqualsAll(int1,int2,int3); 
+6
source share

You can try something like this using the boolean and operator:

 if(int1 == 123 && int2 == 123 && int3 == 123) { } 
+1
source share
 if(int1 == something && int2 == something && int3 == 123) { // Fantastic code here } 

So you have to do this with the && operator. You can check several conditions using this.

UPDATE:

As for checking multiple values ​​at a time, you can try to make an array of these values ​​and just run a simple LINQ statement, like this, to check all of them for a specific value:

 if (new[] { int1, int2, int3 }.All(x => x == 1)) 

I don’t know if this meets your requirement, only an offer.

+1
source share
 if(int1 == 123 && int2 == 123 && int3 == 123) { // Code } 

What you are trying to achieve is impossible as you do it. You must divide it by &.

+1
source share

All Articles