C# 三元运算符列表运算符

C# ternary operator List operator

任何人都知道最快的三元运算。

label1.Text = Cclass.TestMe()
                    .Where(t => t.GFName == (textBox1.Text == "" 
                                              ? "GName" 
                                              : textBox1.Text))
                    .First()
                    .GFName == null ? 
              "Nothing" : 
              "Super";

我正在尝试检查列表是否为空return。所以编译器不会抛出异常或未处理的错误。

这个异常原因First(). It will throw an exception if there's no row to be returned. Instead of that you can use FirstOrDefault() which will return the default value (NULL for all reference types) instead. But if you want to check if there any element inside your list which mathcing the condition, then you must use Any() 扩展方法:

 return Cclass.TestMe()
                .Any(t => t.GFName == (textBox1.Text == "" ? "GName" : textBox1.Text)) ? 
        "Super" : 
        "Nothing";

顺便说一下,最好在查询之外设置文本:

var filteredText = textBox1.Text == "" ? "GName" : textBox1.Text;
return Cclass.TestMe().Any(t => t.GFName == filteredText) ? 
            "Super" : 
            "Nothing";

如果我理解你是对的,如果 where 子句 return 是某种东西,你想要 return 一个值,如果不是,则需要另一个值。那将是:

label1.Text = Cclass.TestMe()
                    .Any(t => t.GFName == (textBox1.Text == "" 
                                              ? "GName" 
                                              : textBox1.Text)) ? 
              "Super" : 
              "Nothing";

如果这不是您想要的,请重新安排您的代码以使用 if 语句使其 有效 ,然后使其 更好 。丑陋的工作代码 总是 比优雅的损坏代码更好。