Equality comparison between multiple variables

前端 未结 14 1297
梦毁少年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:26

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

提交回复
热议问题