加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 简化LINQ表达式

发布时间:2020-12-15 18:05:53 所属栏目:百科 来源:网络整理
导读:我有一部分我真的不喜欢的代码,如果有可能以某种方式简化它 – 会非常好. A a; // I want to get rid of this variableif((a = collection.FirstOrDefault(x = x.Field == null)) != null){ throw new ScriptException("{0}",a.y); //I need to access other
我有一部分我真的不喜欢的代码,如果有可能以某种方式简化它 – 会非常好.
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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读