C # Reduce Abbreviations

I have this code:

    if (y == a && y == b && y == c && y == d ...)
    {
        ...
    }

Is there some form of contraction so that I can rewrite it as something like that?

    if(y == (a && b && c && d ...))
    {
        ...
    }

The functionality should be exactly the same. I'm just looking for something that looks less confusing.

EDIT Sorry for not clarifying, all variables are integers. I'm looking for a shorter way to ensure that a, b, c, d, ... we are all equal y.

+3
source share
9 answers

The closest thing you are going to get (without implementing your own mechanism):

if (new[] { a, b, c, d }.All(value => y == value))
    // ...
+9
source

No , there is nothing that will simplify your code without overloading the benefits of reading with a large performance penalty.


:

, :

(: -, , , generics varargs, , , . int, .)

static bool AllEqual(int value, __arglist)
{
    for (var ai = new ArgIterator(__arglist); ai.GetRemainingCount() > 0; )
    {
        var next = __refvalue(ai.GetNextArg(typeof(int).TypeHandle), int);
        if (!value.Equals(next)) { return false; }
    }
    return true;
}

:

//...
bool equal = AllEqual(1, __arglist(1, 1, 1));

: , , , .:)

+4

( ):

if ((y == a) && (y == b) && (y == c) && (y == d) ...)

.

- , , , :

if (isSetToAll (y, a, b, c, d, ...))

.


, , a/b/c/d/... ( , y).

:

if ((a == b) && (a == c) && (a == d) ...)

, , y . , , :

if (y == a)

, , non y , , y .

, , , .


, verbose, , . :

if ((y == a) && (y == b) && (y == c) && (y == d) &&
    (y == e) && (y == f) && (y == g) && (y == h) &&
    (y == i) && (y == j) && (y == k) && (y == l) &&
    (y == m) && (y == n) && (y == o) && (y == p) &&
    (y == q) && (y == r) && (y == s) && (y == t) &&
    (y == u) && (y == v) && (y == w) && (y == x))
{
    ...
}

( ).

, , .

+3

, . , .

, public static bool AllEqual<T>(params T[] values) (, 2/3/4/5, ), , .

+2

:

,

IList<string> valuesToCompare = new List<string> { "a", "b", "c", "d" };

if (valuesToCompare.Any(valueToCompare => valueToCompare != y)) 
       //If there is any value that is not equal to y
       //Do something
+1
new[] { a, b, c, d }.Contains(y)
0

, , .

, , , , , . , q == y - .

, , , .

, , a, b, c, d 4 : a.x, b.x, c.x, d.x. a, b, c, d? , - -! , 4 5 3.

, , , , , - , , , - .

, . , a, b, c d - , , .

0

For if (y == a & y == b & y == c & y == d) use:

if (y == a == b == c == d) {// code here} Strike>

For if (y == a || y == b || y == c || y == d) , and y is a simple type or string, use:

switch(y)
{
   case a:
   case b:
   case c:
   case d:
     //your code here
     break;

}
-1
source
   bool  x=true ,y=true, z=true, p = true;

    if (x == (y == z == p)) //true

    x = false;
    if (x == (y == z == p)) //false
-3
source

Source: https://habr.com/ru/post/1786030/


All Articles