简化LINQ表达式

Ana*_*ion 6 c# linq

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

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
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*kiy 7

如果要组合变量赋值和定义,则可以使代码更具可读性:

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

if(a != null)    
   throw new ScriptException("{0}", a.y);
Run Code Online (Sandbox Code Playgroud)


Ser*_*rvy 7

而不是找到匹配和处理它的第一个项目,将结果视为集合. foreach覆盖所有匹配使用的项目Where.由于异常将使您退出循环,最终结果是相同的,只需更清晰的代码:

foreach(var a in collection.Where(x => x.Field == null))
    throw new ScriptException("{0}", a.y);
Run Code Online (Sandbox Code Playgroud)

如果你想让读者更清楚,循环最多只执行一次,你可以Take在那里添加一个调用来澄清代码而不做任何功能改变:

foreach(var a in collection.Where(x => x.Field == null).Take(1))
    throw new ScriptException("{0}", a.y);
Run Code Online (Sandbox Code Playgroud)

这也可以更容易地聚合所有无效项,而不是第一个:

var exceptions = collection.Where(a => a.Field == null)
    .Select(a => new ScriptException("{0}", a.y))
    .ToList();
if (exceptions.Any())
    throw new AggregateException(exceptions);
Run Code Online (Sandbox Code Playgroud)