c# - 为什么我可以使用 If Else 语法而不是三元运算符?

标签 c# linq if-statement ternary-operator

为什么我可以这样做?

if (integerList.Direction == "ascending") { 
    integerList.Integers.OrderBy(i => i.IntegerValue);
} else{
    integerList.Integers.OrderByDescending(i => i.IntegerValue);
}

但不是这个?

integerList.Direction == "ascending" ? integerList.Integers.OrderBy(i => i.IntegerValue)
                                     : integerList.Integers.OrderByDescending(i => i.IntegerValue);

它返回错误:

only assignment, call, increment, decrement, await and new object expressions can be used as a statement.

最佳答案

因为这段代码调用了给定的操作(不管分支),这本身就是一个语句,因此是允许的,

if (integerList.Direction == "ascending") { 
    integerList.Integers.OrderBy(i => i.IntegerValue);
} else{
    integerList.Integers.OrderByDescending(i => i.IntegerValue);
}

然而,使用三元运算符,你最终会得到一个表达式,它本身是不允许的,因为它被认为是一个空操作,当然除了,如错误所说,它是一个新的对象表达式,

integerList.Direction == "ascending" 
    ? integerList.Integers.OrderBy(i => i.IntegerValue)
    : integerList.Integers.OrderByDescending(i => i.IntegerValue);

操作的结果它并没有被实际消费,所以整个OrderBy都被浪费了。

试试这个,

var intergersOrdered = 
    integerList.Direction == "ascending" 
        ? integerList.Integers.OrderBy(i => i.IntegerValue)
        : integerList.Integers.OrderByDescending(i => i.IntegerValue);

将三元运算符转换为赋值语句。

关于c# - 为什么我可以使用 If Else 语法而不是三元运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19148835/

相关文章:

c# - 如何在嵌套 ListView 中编辑数据

javascript - isNaN 似乎无法正常工作

Python 2.7,如何获取/检查列表的大小?

c# - 验证已执行的事件处理程序代码

c# - Entity Framework Core - 如何访问 Context.Database.Migrate()

c# - 从 DataTable 中的行创建一系列匿名类型

if-statement - 我可以在 LibreOffice calc IF 语句中使用 OR 吗?

c# - 向 C# 命名空间添加描述

c# - Unity 4.6 编辑器,使用预定义数据创建脚本

c# - 遍历两个列表