Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to compare values of more than 3 variables?

Tags:

c#

comparison

I want to check whether these variables have same values.

EXAMPLE:

int a = 5;
int b = 5;
int c = 5;
int d = 5;
int e = 5;
. . .
int k = 5;

if(a==b && b==c && c==d && d==e && .... && j==k)  
{
   //this is Complex way and not well understandable.
}

Any easy way to Compare all are same?
LIKE in below example

if(a==b==c==d==e.....j==k)
{
    //Understandable but not work 
}
like image 335
Javed Akram Avatar asked Mar 04 '11 01:03

Javed Akram


3 Answers

how about something like this:

if (Array.TrueForAll<int>(new int[] {a, b, c, d, e, f, g, h, i, j, k },
        val => (a == val))) {
    // do something
}
like image 106
mellamokb Avatar answered Sep 28 '22 02:09

mellamokb


With this many variables, would it make sense to move them into an array?

You could then test to see if they are all equal using Linq expressions like myarray.Distinct().Count() == 1; or perhaps myarray.All(r => r == 5);

like image 35
dthorpe Avatar answered Sep 28 '22 02:09

dthorpe


You could create a var args method to do that:

bool intsEqual (params int[] ints) { 
   for (int i = 0; i < ints.Length - 1; i++) {
       if (ints[i] != ints[i+1]) {
          return False;
       }
   }
   return True;
}

Then just call it with all your ints as parameters:

if (intsEqual(a, b, c, d, e, f, g, h, i, j, k)) {
    doSomeStuff();
}
like image 30
Kaleb Brasee Avatar answered Sep 28 '22 03:09

Kaleb Brasee