BakeryD
BakeryD

Reputation: 3

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?

Upvotes: 0

Views: 162

Answers (1)

Guru Stron
Guru Stron

Reputation: 142913

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);
}

Upvotes: 3

Related Questions