Enumerable.Any()和可能的多个枚举

Rider / Resharper给了我有关此的多个枚举警告:

public void ProcessProductCodes(IEnumerable<string> productCodes) {
    if (productCodes.Any()) {
        DoStuff(productCodes);
    }
}

是误报,还是Any()函数确实弄乱了集合的枚举?

评论
你带走了爱
你带走了爱

The IEnumerable interface represents a sequence of items that can be iterated over, but makes no assumptions about the origin of the sequence. For instance, it could be a database query. If that was the case, here you would make 2 calls to the database, one for checking if there is any item in the sequence and another one to pass them to the DoStuff function, which obviously is not optimal performance-wise, and Resharper is warning you about this.

为避免此问题,您有2种不同的选择。如果项目集合已经在内存中,则可以通过将函数的签名更改为以下方式使其明确:

public void ProcessProductCodes(ICollection<string> productCodes) { ... }

If you cannot guarantee this, you can do a .ToList() or .ToArray at the beginning of your function:

public void ProcessProductCodes(IEnumerable<string> productCodes) {
  var productCodesList = productCodes.ToList();
  if (productCodesList .Any()) {
      DoStuff(productCodesList );
  }

Resharper will do this for you, just select the quick refactoring (usually with Alt+Enter).

点赞
评论