繁体   English   中英

C#Linq可能的多种枚举最佳实践

[英]C# linq possible multiple enumeration best practices

有时我在C#源代码中使用LINQ构造。 我将VS 2010与ReSharper一起使用。 现在,我从ReSharper收到“可能的IEnumerable多重枚举”警告。

我想根据最佳实践对其进行重构。 简要介绍一下它的作用:

IEnumerable<String> codesMatching = from c in codes where conditions select c;
String theCode = null;
if (codesMatching.Any())
{
  theCode = codesMatching.First();
}
if ((theCode == null) || (codesMatching.Count() != 1))
{
  throw new Exception("Matching code either not found or is not unique.");
}
// OK - do something with theCode.

一个问题:我应该首先将LINQ表达式的结果存储在List中吗? (我很确定它不会返回多于几行-最多说10行。)

任何提示表示赞赏。

谢谢帕维尔

是的,您需要将结果存储为List \\ Array,然后使用它。 在这种情况下,它将不会枚举两次。

在您的情况下,如果您需要确保只有一项满足条件,则可以使用“ Single -如果有一项以上满足条件,则会抛出异常。 如果根本没有任何项目,它也会引发异常。

而且您的代码将更容易:

string theCode = (from c in codes where conditions select c).Single();

但是在这种情况下,您无法更改异常文本,或者需要将其包装到自己的try \\ catch块中,然后使用自定义文本\\ exception将其重新抛出

由于要验证条件是否唯一,因此可以尝试执行此操作(是的,必须存储结果):

var codes = (from c in codes where conditions select c).Take(2).ToArray();
if (codes.Length != 1)
{
  throw new Exception("Matching code either not found or is not unique.");
}

var code = codes[0];

.ToList() / .ToArray() .ToList()可枚举将摆脱警告,但是要了解它是否优于多个枚举,将取决于codesconditions实现。 .Any().First()是惰性原语,不会执行到第一个元素之后,并且.Count()可能根本不会被命中,因此转换为列表可能比获取新的枚举器更为浪费。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM