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 is the meaning of that?
这是一个三元运算符。它将if-else-return
封装在一行中。
这是 C# 条件运算符。
它允许您指定一个条件和两个表达式。当条件为真时,返回第一个表达式。当条件为假时,返回第二个表达式。在这种情况下,您将其用作条件:
Math.Abs(x-number) < Math.Abs(y-number)
当条件成立时,返回x
,否则返回y
。上面创建的lambda表达式实际上等同于以下代码:
int closest = list.Aggregate((x,y) =>
{
if (Math.Abs(x-number) < Math.Abs(y-number))
return x;
else
return y;
});
其实? 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
a ? b : c
是一个三元运算符,它的翻译是:
if(a)
b;
else
c;
b
和c
不是语句,而是表达式。 - Pindatjuh?
- 如果?
左侧的条件为真,则返回x
,如果条件为假,则返回y
。这与以下内容相同:
if (Math.Abs(x-number) < Math.Abs(y-number))
return x;
else
return y;
这是一个三元运算符
if(Math.Abs(x-number) < Math.Abs(y-number))
true
else
false
.
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) => 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;
}
});