本文翻译自:Handling warning for possible multiple enumeration of IEnumerable
In my code in need to use an IEnumerable<>
several times thus get the Resharper error of "Possible multiple enumeration of IEnumerable
". 在我的代码中需要使用IEnumerable<>
几次因此得到Resharper错误“可能多次枚举IEnumerable
”。
Sample code: 示例代码:
public List<object> Foo(IEnumerable<object> objects)
{
if (objects == null || !objects.Any())
throw new ArgumentException();
var firstObject = objects.First();
var list = DoSomeThing(firstObject);
var secondList = DoSomeThingElse(objects);
list.AddRange(secondList);
return list;
}
- I can change the
objects
parameter to beList
and then avoid the possible multiple enumeration but then I don't get the highest object that I can handle. 我可以将objects
参数更改为List
,然后避免可能的多次枚举,但后来我没有得到我能处理的最高对象。 - Another thing that I can do is to convert the
IEnumerable
toList
at the beginning of the method: 我能做的另一件事是在方法的开头将IEnumerable
转换为List
:
public List<object> Foo(IEnumerable<object> objects)
{
var objectList = objects.ToList();
// ...
}
But this is just awkward . 但这只是尴尬 。
What would you do in this scenario? 在这种情况下你会做什么?
#1楼
参考:https://stackoom.com/question/YZoq/处理可能多次枚举IEnumerable的警告
#2楼
I usually overload my method with IEnumerable and IList in this situation. 在这种情况下,我通常使用IEnumerable和IList重载我的方法。
public static IEnumerable<T> Method<T>( this IList<T> source ){... }
public static IEnumerable<T> M