Rider / Resharper给了我有关此的多个枚举警告:
public void ProcessProductCodes(IEnumerable<string> productCodes) {
if (productCodes.Any()) {
DoStuff(productCodes);
}
}
是误报,还是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 theDoStuff
function, which obviously is not optimal performance-wise, and Resharper is warning you about this.为避免此问题,您有2种不同的选择。如果项目集合已经在内存中,则可以通过将函数的签名更改为以下方式使其明确:
If you cannot guarantee this, you can do a
.ToList()
or.ToArray
at the beginning of your function:Resharper will do this for you, just select the quick refactoring (usually with
Alt+Enter
).