Marek
Marek

Reputation: 261

Does for loop count elements added into itself during the loop?

My question is, that when I loop through a list with for loop, and add elements to it during this, does it count the elements added while looping? Simple code example:

for (int i = 0; i < listOfIds.Count(); i++) // Does loop counts the items added below?
{
    foreach (var post in this.Collection)
    {
        if (post.ResponsePostID == listOfIds.ElementAt(i))
        {
            listOfIds.Add(post.PostId); // I add new item to list in here
        }
    }
}

I hope my explanation is good enough for you to understand what my question is.

Upvotes: 2

Views: 400

Answers (4)

Chris
Chris

Reputation: 8656

As a slightly abridged explanation of the for loop. You're essentially defining the following:

for (initializer; condition; iterator)
body

Your initializer will will establish your initial conditions, and will only happen once (effectively outside the loop).

Your condition will be evaluated every time to determine whether your loop should run again, or simply exit.

Your iterator defines an action that will occur after each iteration in your loop.

So in your case, your loop will reevaluate listOfIds.Count(); each time, to decide if it should execute; that may or may not be your desired behaviour.

As Dennis points out, you can let yourself get into a bit of a mess (youy loop may run infinitely) if you aren't careful.

A much more detailed/better written explanation can be found on msdn: http://msdn.microsoft.com/en-us/library/ch45axte.aspx

Upvotes: 0

Sujay
Sujay

Reputation: 426

Yes it surely will.The inner foreach loop will execute and add the elements the outer collection and thus will increament the count of the elements.

listOfIds.Count=2 //iteration 1

listOfIds.Add(//element)

when it come to the for loop again

listOfIds.Count=3 //iteration 2

Upvotes: 0

Dennis Traub
Dennis Traub

Reputation: 51634

Yes, it usually does. But changing a collection at the same time you're iterating over it can lead to weird behavior and hard-to-find bugs. It isn't recommended at all.

Upvotes: 8

Rajeev Kumar
Rajeev Kumar

Reputation: 4963

If you want this loop run only for preAdded item count then do this

int nLstCount =  listOfIds.Count();
for (int i = 0; i < nLstCount ; i++) 
{
foreach (var post in this.Collection)
{
    if (post.ResponsePostID == listOfIds.ElementAt(i))
    {
        listOfIds.Add(post.PostId);
    }
}
}

Upvotes: 0

Related Questions