In my code I need to use an IEnumerable<> several times, resulting in the ReSharper error of “Possible multiple enumeration of 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 be List and then avoid the possible multiple enumeration but then I don’t get the highest object that I can handle.
  • Another thing that I can do is to convert the IEnumerable to List at the beginning of the method:

 public List<object> Foo(IEnumerable<object> objects)
 {
    var objectList = objects.ToList();
    // ...
 }

But this is just awkward.

What would you do in this scenario?

9 Answers
9

Leave a Reply

Your email address will not be published. Required fields are marked *