Is there a shorter way of testing the following:
if (!((a == b) && (a == c) && (a == d) && (a == e) && (a == f)))
I ended up writing a method that lets me do this
if (!AllEqual(new[] { a, b, c, d, e, f }))
That feels nicer and is a lot more readable, but I'm wondering if there is something in the framework that does this already?
Well for one thing, you can use a parameter array to make it simpler:
public static bool AllEqual<T>(params T[] values)
...
if (AllEqual(a, b, c, d, e, f))
{
...
}
I don't think you'll find anything simpler than that, to be honest. I haven't seen this anywhere else, or in the framework. Well, I suppose there's one thing you could do in LINQ:
if (new { a, b, c, d, e, f }.Distinct().Count() == 1)
But that's pretty horrible :)
A slightly more efficient version of that is:
if (!(new { a, b, c, d, e, f }).Distinct().Skip(1).Any()))
... which will return false as soon as it finds the second distinct element. With only 6 elements I don't think it's worth worrying though :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With