? x: y, what's the point of this?

List<int> list = new List<int> { 2, 5, 7, 10 };
int number = 9;

int closest = list.Aggregate((x,y) => 
    Math.Abs(x-number) < Math.Abs(y-number) ? x : y);

? x: y, what's the point of this?

+3
source share
10 answers

this is the equivalent

if Math.Abs(x-number) < Math.Abs(y-number) then use x else use y

See the MSDN documentation ( old version / new version ) for more information and examples.

+9
source

This is a ternary operator. It encloses if-else-returnin one line.

+7
source

#.

. , . , . :

Math.Abs(x-number) < Math.Abs(y-number) 

, x, false, y. , , , :

int closest = list.Aggregate((x,y) => 
    {
        if (Math.Abs(x-number) < Math.Abs(y-number))
            return x;
        else
            return y;
    });
+5

, ? x : y

, , if/else. :

<boolean_expression> ? <value_to_use_if_true> : <value_to_use_if_false>

:

 Math.Abs(x-number) < Math.Abs(y-number)

true, :

x

:

y
+3

a ? b : c , :

if(a)
    b;
else
    c;
+2

? - LHS ? , x - false, y

+1

BoolOpeartor? TrueEval: FalseEval;

+1

, :

if (Math.Abs(x-number) < Math.Abs(y-number)) 
    return x; 
else 
    return y;
+1

if(Math.Abs(x-number) < Math.Abs(y-number))
  true
else
  false  

        .

Math.Abs(x-number) < Math.Abs(y-number) ? x : y
0

:

List<int> list = new List<int> { 2, 5, 7, 10 };
int number = 9;
int closest = list.Aggregate((x,y) => Math.Abs(x-number) < Math.Abs(y-number) ? x : y);

:

List<int> list = new List<int> { 2, 5, 7, 10 };
int number = 9;
int closest = list.Aggregate((x,y) => 
{
    if(Math.Abs(x-number) < Math.Abs(y-number))
    {
        return x;
    }
    else
    {
        return y;
    }
});

What you use is called a conditional statement, which is an abbreviation for the if-else statement, where the return result is selected as follows: {true / false condition}? {value if true}: {value if false}

0
source

All Articles