Search code examples
c#linqenumerationdeferred-execution

Am I enumerating my IEnumerable<T> n times?


I am fairly comfortable with LINQ in c#, but am lost on whether or not my foreach loop is causing excessive enumeration.

Assuming the following code snippet is run,

var listOfStuff = new List<CustomObject>
{
    new CustomObject { Id = 1, Cost = 20M },
    new CustomObject { Id = 2, Cost = 11M },
    new CustomObject { Id = 3, Cost = 3.75M },
    new CustomObject { Id = 4, Cost = 50.99M }
};
var newObjects = listOfStuff.Select(thing =>
    new AnotherObject { Id = x.ID, NegaCost = decimal.Negate(x.Cost) });

foreach (var i in n) // a list of objects with a length of n
{
   var match = newObjects.Where(PreDefinedPredicate);
   i.DoSomethingWith(match);
}

is a new AnotherObject instance being created n times or am i misunderstanding the concept of multiple enumerations?


Solution

  • It depends what do you do with match in i.DoSomethingWith, but if you are iterating it in there, then yes.

    You can always check you assumption introducing some side-effect like Console.WriteLine:

    var newObjects = listOfStuff.Select(x =>
        {
             Console.WriteLine($"Here with id: {x.Id}"); // SIDEEFFECT
             return new AnotherObject { Id = x.ID, NegaCost = decimal.Negate(x.Cost) };
        });
    
    foreach (var i in n) // a list of objects with a length of n
    {
       var match = newObjects.Where(PreDefinedPredicate);
       i.DoSomethingWith(match);
    }