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
if (x == y && y == z && z == 1)
There are no other simple or more efficient ways.
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.");
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.
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)) { ... }
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;
}
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;
}
}