? x:y,那是什么意思?

时间:2011-05-10 19:11:44

标签: c# .net

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,那是什么意思?

10 个答案:

答案 0 :(得分:9)

相当于

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

有关更多详细信息和示例,请参阅MSDN文档(old version / new version

答案 1 :(得分:7)

这是ternary运营商。它将if-else-return封装在一行中。

答案 2 :(得分:5)

那是C# conditional operator

它允许您指定条件和两个表达式。条件为true时,返回第一个表达式。如果为false,则返回第二个表达式。在这种情况下,您使用此作为条件:

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

如果是这样,则返回x,如果为false,则返回y。上面创建的lambda实际上与写作相同:

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

答案 3 :(得分:3)

实际上它比? 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

答案 4 :(得分:2)

a ? b : c是三元运算符,它转换为:

if(a)
    b;
else
    c;

答案 5 :(得分:1)

三元运算符? - 如果?的LHS条件为真,则返回x - 如果条件为false,则返回y

答案 6 :(得分:1)

那是conditional operator

BoolOpeartor? TrueEval:FalseEval;

答案 7 :(得分:1)

它与:

相同
if (Math.Abs(x-number) < Math.Abs(y-number)) 
    return x; 
else 
    return y;

答案 8 :(得分:0)

ternary运营商

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

        .
  

或者只是

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

答案 9 :(得分: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;
    }
});

您正在使用的是条件运算符,它是if-else语句的简写表示法,其中返回的结果选择如下: {true / false condition}? {value if true}:{value if false}

相关问题