gpt4 book ai didi

c# - 简化 LINQ 表达式

转载 作者:太空狗 更新时间:2023-10-29 20:51:30 26 4
gpt4 key购买 nike

我有一部分代码我真的不喜欢,如果有可能以某种方式简化它 - 会非常好。

A a; // I want to get rid of this variable
if((a = collection.FirstOrDefault(x => x.Field == null)) != null)
{
throw new ScriptException("{0}", a.y); //I need to access other field of the object here, that's why I had to declare a variable outside of the expression
}

最佳答案

如果将变量赋值和定义结合起来,可以使代码更具可读性:

A a = collection.FirstOrDefault(x => x.Field == null);

if(a != null)
throw new ScriptException("{0}", a.y);

关于c# - 简化 LINQ 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19545716/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com