Say I have 3 char
variables, a
, b
and c
.
Each one can be '0'
, which is a special case and means it matches every char.
So if a is '0'
, I only need to check if b == c
.
I want to check if a == b == c
, but found the implementation in C# goes chaotic and lengthy.
Is there any creative or pretty solution you can offer?
update
for performance driven, take Erik A. Brandstadmoen's approach.
for simplicity, use M4N's apprach, also i did some modification: !(query.Any() && query.Distinct().Skip(1).Any())
To have a comparison of three (or more) variables done correctly, one should use the following expression: if (a == b && b == c) .... In this case, a == b will return true, b == c will return true and the result of the logical operation AND will also be true.
You can, but it's unimpressive. The program compares variables a and b and gets the result, TRUE or FALSE. Then it compares b and c and gets the result, TRUE or FALSE. Then it compares those two results: TRUE && TRUE is what you need to see if all variables are equal to each other; TRUE && TRUE evaluates to TRUE.
a() == b() == c() is functionally equivalent to a() == b() and b() == c() whenever consecutive calls to b return the same value and have the same aggregate side effects as a single call to b . For instance, there is no difference between the two expressions whenever b is a pure function with no side-effects.
The is keyword is used to test if two variables refer to the same object. The test returns True if the two objects are the same object. The test returns False if they are not the same object, even if the two objects are 100% equal. Use the == operator to test if two variables are equal.
Something like this:
var a = '1';
var b = '0';
var c = '1';
var chars = new List<char> { a, b, c };
var filtered = chars.Where(ch => ch != '0');
var allEqual = filtered.Count() == 0 || filtered.Distinct().Count() == 1;
To explain the solution:
.Where(ch => ch != '0')
chars.Count() == 0
chars.Distinct().Count() == 1
Update: here's a different version, which does not use LINQ but is still and readable (IMO). It is implemented as a method and can be called with any number of characters to be tested:
public bool AllEqualOrZero(params char[] chars)
{
if (chars.Length <= 1) return true;
char? firstNonZero = null;
foreach (var c in chars)
{
if (c != '0')
{
firstNonZero = firstNonZero ?? c;
if (c != firstNonZero) return false;
}
}
}
// Usage:
AllEqualOrZero('0', '0', '0'); // -> true
AllEqualOrZero('0', '1', '1'); // -> true
AllEqualOrZero('2', '1', '0'); // -> false
AllEqualOrZero(); // -> true
AllEqualOrZero('1'); // -> true
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