Tutorial :Equality comparison between multiple variables



Question:

I've a situation where I need to check whether multiple variables are having same data such as

var x=1;  var y=1;  var z=1;  

I want to check whether x==1 and y==1 z==1 (it may be '1' or some other value). instead of this, is there any short way I can achieve same such as below

if(x==y==z==1)  

Is this possible in C#?


Solution:1

KennyTM is correct, there is no other simpler or more efficient way.

However, if you have many variables, you could also build an array of the values and use the IEnumerable.All method to verify they're all 1. More readable, IMO.

if (new[] { v1, v2, v3, v4, v5, v6, v7, v8, v9, v10 }.All(x => x == 1))  

Instead of

if(v1 == 1 && v2 == 1 && v3 == 1 && v4 == 1 && v5 == 1 && v6 == 1 && v7 == 1 && v8 == 1 && v9== 1 && v10 == 1)  


Solution:2

if (x == y && y == z && z == 1)  

is the best you can do, because

y == z evaluates to a boolean and you can't compare x with the result:

x == (y == z)    |    |    int  bool  

I would do this:

public bool AllEqual<T>(params T[] values) {      if(values == null || values.Length == 0)           return true;      return values.All(v => v.Equals(values[0]));      }    // ...    if(AllEqual(x, y, z)) { ... }  


Solution:3

If you just want to testif x == y == z you can use:

var allEqual = new[] {x, y, z}.Distinct().Count() == 1;  

If you want to test if they're all equal to 1, add 1 to the set:

var allEqual1 = new[] {x, y, z, 1}.Distinct().Count() == 1;  

or use All as in fencliff's answer.


Solution:4

if (x == y && y == z && z == 1)  

There are no other simple or more efficient ways.


Solution:5

For integral types, what about:

int x = 3, y = 3, z = 3;    if((x & y & z & 3) == 3)    //...have same data  

for testing any non-zero value. It would need more checks to make this a re-usable function. But might work for inline checks of non-zero equality, as the OP described.


Solution:6

Here's a nice little recursive solution that works with all types.

class Program  {      static void Main(string[] args)      {          int x = 4, y = 4, z = 4;          Console.WriteLine(4.IsEqualToAllIn(x, y, z).ToString());          //prints True            string a = "str", b = "str1", c = "str";          Console.WriteLine("str".IsEqualToAllIn(a, b, c).ToString());          //prints False      }  }    public static class MyExtensions  {      public static bool IsEqualToAllIn<T>(this T valueToCompare, params T[] list)      {          bool prevResult = true;          if (list.Count() > 1)              prevResult = list[0].IsEqualToAllIn(list.Skip(1).ToArray());          return (valueToCompare.Equals(list[0])) && prevResult;      }  }  


Solution:7

public static bool AllSame<T>(List<T> values)  {      return values.Distinct().Count() == 1;  }    public static bool AllDifferent<T>(List<T> values)  {      return values.Distinct().Count() == values.Count;  }  


Solution:8

XOR might work for you, e.g. given:

var x=1;  var y=1;  var z=1;  

Then

x ^ y ^ z == 0  

Is true

-edit- If you want to check if all values are the same and their value is 1, use:

x ^ y ^ z ^ 1 == 0  


Solution:9

Add this extension:

public static class Extensions  {      public static bool EqualsAll<T>(this T subject, params T[] values) =>          values == null || values.Length == 0 || values.All(v => v.Equals(subject));  }  

Then call it like so:

if(1.EqualsAll(x, y, z))  


Solution:10

Actually i don't have to the time to code, but an extension method with linq like this

public bool EqualsToAll<T>(this T element, IEnumerable<T> source)  {      if(element == null)          throw new ArgumentNullException(element);        foreach(var item in source)      {          if(!element.Equals(item)              return false;      }        return true;  }  

should make it.

Warning: This code was not tested, nor written within an IDE.


Solution:11

var x = 1;  var y = 1;  var z = 1;    if (AllEqual(1, x, y, z))    // true  if (AllEqual(2, x, y, z))    // false  if (AllEqual(x, y, z))       // true    var a = 1;  var b = 2;  var c = 3;    if (AllEqual(a, b, c))       // false    // ...    public static bool AllEqual<T>(params T[] values)  {      if (values == null)          throw new ArgumentNullException("values");        if (values.Length < 1)          throw new ArgumentException("Values cannot be empty.", "values");        T value = values[0];      for (int i = 1; i < values.Length; i++)      {          if (!value.Equals(values[i]))              return false;      }      return true;  }  


Solution:12

I adapted Mau's solution into an extension method. It would be nice if they added this to the framework for all value types.

public static class IntegerExtensions  {      public static bool EqualsAll(this int subject, params int[] values)      {          if (values == null || values.Length == 0)          {              return true;          }            return values.All(v => v == subject);      }  }  


Solution:13

There is how I did this:

Debug.Assert(new List<int> { l1.Count, l2.Count, l3.Count, l4.Count }.TrueForAll(    delegate(int value) { return value == l1.Count; }), "Tables have different size.");  


Solution:14

Slight variation on the excellent answer given by jevakallio above. See if myValue is equal to any of the values in a list (in the array):

if (new[] { 10, 11, 12 }.Any(x => x == myValue))  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »