Easy way to compare values of more than 3 variables?

25,339

Solution 1

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
}

Solution 2

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();
}

Solution 3

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

Solution 4

Just a thought, but if you can calculate the standard deviation of the entire list, and it is equal to zero, you would have your answer.

Here's an answer on the site that addresses this that may help with that: Standard deviation of generic list?

Interesting problem. Good luck with it.

Solution 5

I agree that the easiest way is to place them all into a list and then use the following to compare. This is in essence looping through and comparing to the first value, but this is a little cleaner.

var match = counts.All(x => x == counts[0])
Share:
25,339
Javed Akram
Author by

Javed Akram

Updated on July 15, 2022

Comments

  • Javed Akram
    Javed Akram almost 2 years

    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 
    }