Equality comparison between multiple variables

前端 未结 14 1104
梦毁少年i
梦毁少年i 2020-11-29 08:00

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

相关标签:
14条回答
  • 2020-11-29 08:34
    if (x == y && y == z && z == 1)
    

    There are no other simple or more efficient ways.

    0 讨论(0)
  • 2020-11-29 08:36

    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.");
    
    0 讨论(0)
  • 2020-11-29 08:40

    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.

    0 讨论(0)
  • 2020-11-29 08:42
    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)) { ... }
    
    0 讨论(0)
  • 2020-11-29 08:42
    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;
    }
    
    0 讨论(0)
  • 2020-11-29 08:48

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题