By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,831 Members | 1,031 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,831 IT Pros & Developers. It's quick & easy.

Reset a foreach loop.

P: n/a
Is there any way to reset a foreach loop to re-iterate through the
collection as if it were starting from the beginning? Namely, if I delete
an item out of a collection, I want to be able to reset the loop.

--
-----------------------------------
Ken Varn
Senior Software Engineer
Diebold Inc.

EmailID = varnk
Domain = Diebold.com
-----------------------------------
Nov 17 '05 #1
Share this Question
Share on Google+
18 Replies


P: n/a
"Ken Varn" <nospam> wrote in news:up**************@TK2MSFTNGP14.phx.gbl:
Is there any way to reset a foreach loop to re-iterate through the
collection as if it were starting from the beginning? Namely, if I
delete an item out of a collection, I want to be able to reset the
loop.


No, you need to use a for loop or a while loop.
--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programming is an art form that fights back"

Empower ASP.NET with IntraWeb
http://www.atozed.com/IntraWeb/
Nov 17 '05 #2

P: n/a
"Ken Varn" <nospam> wrote in message
news:up**************@TK2MSFTNGP14.phx.gbl...
Is there any way to reset a foreach loop to re-iterate through the
collection as if it were starting from the beginning? Namely, if I delete
an item out of a collection, I want to be able to reset the loop.


I have to say I disagree with a for loop that iterates through a collection
and then changes the collection in the loop. However if you must do it,
wrap the for loop inside of a while loop (while (1=1)) that doesn't end.

while (1==1)
{
foreach (...)
{
if (item_deleted_from_collection)
{
item_deleted = true;
break;
}
}
if (not item_deleted)
break;
}

HTH,

Mike Rodriguez
Nov 17 '05 #3

P: n/a
Just curious, what is the end result that you are trying to accomplish?
Perhaps there is a better way.
"Ken Varn" <nospam> wrote in message
news:up**************@TK2MSFTNGP14.phx.gbl...
Is there any way to reset a foreach loop to re-iterate through the
collection as if it were starting from the beginning? Namely, if I delete
an item out of a collection, I want to be able to reset the loop.

--
-----------------------------------
Ken Varn
Senior Software Engineer
Diebold Inc.

EmailID = varnk
Domain = Diebold.com
-----------------------------------

Nov 17 '05 #4

P: n/a
"Ken Varn" <nospam> wrote in message
news:up**************@TK2MSFTNGP14.phx.gbl...
Is there any way to reset a foreach loop to re-iterate through the
collection as if it were starting from the beginning? Namely, if I delete
an item out of a collection, I want to be able to reset the loop.


It's possibly better to go backwards through the collection in a normal for
loop and remove items as necessary.

Why do you need to start over completely, if you remove an item couldn't you
still continue on?

Michael
Nov 17 '05 #5

P: n/a
That's what I was getting at as well, also, in the default enumerator
implementations, don't you get an exception when you modify a collection
that you are enumerating with foreach?

"Michael C" <mc*****@NOSPAMoptushome.com.au> wrote in message
news:er**************@TK2MSFTNGP15.phx.gbl...
"Ken Varn" <nospam> wrote in message
news:up**************@TK2MSFTNGP14.phx.gbl...
Is there any way to reset a foreach loop to re-iterate through the
collection as if it were starting from the beginning? Namely, if I
delete
an item out of a collection, I want to be able to reset the loop.


It's possibly better to go backwards through the collection in a normal
for loop and remove items as necessary.

Why do you need to start over completely, if you remove an item couldn't
you still continue on?

Michael

Nov 17 '05 #6

P: n/a
I don't believe you can reset the foreach loop inside the loop, or continue
after you have modified the collection. About the best you can do is:

bool more = true;
while (collect.Count > 0 && more)
{
more = false;
foreach (Typ t in collect)
{
if (something)
{
collect.Remove(t);
more = true;
break;
}
}
}

or words to that effect <G>.

"J.Marsch" <jm*****@newsgroup.nospam> wrote in message
news:e9*************@TK2MSFTNGP09.phx.gbl...
That's what I was getting at as well, also, in the default enumerator
implementations, don't you get an exception when you modify a collection
that you are enumerating with foreach?

"Michael C" <mc*****@NOSPAMoptushome.com.au> wrote in message
news:er**************@TK2MSFTNGP15.phx.gbl...
"Ken Varn" <nospam> wrote in message
news:up**************@TK2MSFTNGP14.phx.gbl...
Is there any way to reset a foreach loop to re-iterate through the
collection as if it were starting from the beginning? Namely, if I
delete
an item out of a collection, I want to be able to reset the loop.


It's possibly better to go backwards through the collection in a normal
for loop and remove items as necessary.

Why do you need to start over completely, if you remove an item couldn't
you still continue on?

Michael


Nov 17 '05 #7

P: n/a
> while (1==1)

Goto are evil, and renaming a goto doesn't make it any less evil,
particular when there's no reason for it in your code:
do
{
foreach (...)
{
if (item_deleted_from_collection)
{
item_deleted = true;
break;
}
}
} while (item_deleted)
--
Truth,
James Curran
[erstwhile VC++ MVP]

Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com

"Michael Rodriguez" <mi**@nospamforme.com> wrote in message
news:#L**************@TK2MSFTNGP12.phx.gbl... "Ken Varn" <nospam> wrote in message
news:up**************@TK2MSFTNGP14.phx.gbl...
Is there any way to reset a foreach loop to re-iterate through the
collection as if it were starting from the beginning? Namely, if I delete an item out of a collection, I want to be able to reset the loop.

I have to say I disagree with a for loop that iterates through a

collection and then changes the collection in the loop. However if you must do it,
wrap the for loop inside of a while loop (while (1=1)) that doesn't end.

while (1==1)
{
foreach (...)
{
if (item_deleted_from_collection)
{
item_deleted = true;
break;
}
}
if (not item_deleted)
break;
}

HTH,

Mike Rodriguez

Nov 17 '05 #8

P: n/a
James Curran <ja*********@mvps.org> wrote:
while (1==1)


Goto are evil, and renaming a goto doesn't make it any less evil,
particular when there's no reason for it in your code:
do
{
foreach (...)
{
if (item_deleted_from_collection)
{
item_deleted = true;
break;
}
}
} while (item_deleted)


Personally I don't like do/while instead of just plain while:

while (keepGoing)
{
foreach (...)
{
if (item_deleted_from_collection)
{
keepGoing = false;
break;
}
}
}

I don't like to have to wait until the end of loop to find out how long
I'm going to have to run the loop for :)

Could be just me though...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #9

P: n/a

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Personally I don't like do/while instead of just plain while:

while (keepGoing)
{
foreach (...)
{
if (item_deleted_from_collection)
{
keepGoing = false;
break;
}
}
}

I don't like to have to wait until the end of loop to find out how long
I'm going to have to run the loop for :)

I tend to prefer while/do as well
However, I think you have a logic error in your version. It stops after the
first delete.
How about:

bool keepGoing = false;
while (!keepGoing)
{
keepGoing = true;
foreach (...)
{
if (item_deleted_from_collection)
{
keepGoing = false;
break;
}
}
}

Bill
Nov 17 '05 #10

P: n/a
Bill Butler <bi**@DA.com> wrote:
I tend to prefer while/do as well
However, I think you have a logic error in your version. It stops after the
first delete.
How about:


Sorry, yes, you're right. That just shows that I shouldn't post code
when ill :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #11

P: n/a
Hello,
As far as I know, if you try to remove an item inside the foreach an
exception will occur as the enumerator gets corrupted for the foreach
loop.

HTH. Cheers :)
Maqsood Ahmed [MCP,C#]
Kolachi Advanced Technologies
http://www.kolachi.net

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #12

P: n/a
Maqsood Ahmed <ma***********@gmail.com> wrote in news:#NeNKL8dFHA.1660
@TK2MSFTNGP10.phx.gbl:
As far as I know, if you try to remove an item inside the foreach an
exception will occur as the enumerator gets corrupted for the foreach
loop.


It depends on how the enumerator is implemented, but I agree its not a wise thing to try.
--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programming is an art form that fights back"

Develop ASP.NET applications easier and in less time:
http://www.atozed.com/IntraWeb/
Nov 17 '05 #13

P: n/a
"Ken Varn" <nospam> wrote in message news:up**************@TK2MSFTNGP14.phx.gbl...
Is there any way to reset a foreach loop to re-iterate through the
collection as if it were starting from the beginning? Namely, if I delete
an item out of a collection, I want to be able to reset the loop.


Hi Ken,

So far we have all discussed various work-arounds to this issue.
Now, I would like to suggest that you take a different approach.

I call it "The Hit List" or "Death Row" and it works like this

----------- Pseudocode -----------
ArrayList HitList = new HitList();
foreach (Thing thing in YourCollection)
{
if (NeedsKilling(thing))
{
HitList.Add(thing);
}
else
{
Process(thing);
}
}
foreach(Thing victim in HitList)
{
YourCollection.Remove(victim);
}
-------------------------------------
Advantages
------------
This algorithm is O(n) as opposed to the others which were O(n^2).
You only loop through the collection once so you can do other processing as well.
------------

It would be nice to have something like remove_if() from the C++ STL.

Hope this helps
Bill

Nov 17 '05 #14

P: n/a
IIRC, Remove iterates the list too until it finds the object. So you
iterate once for the hitlist and one for item in the hitlist. I would agree
this is probably the best way however.

--
William Stacey [MVP]

"Bill Butler" <qw****@asdf.com> wrote in message
news:7JKue.6432$PZ6.4885@trndny08...
"Ken Varn" <nospam> wrote in message
news:up**************@TK2MSFTNGP14.phx.gbl...
Is there any way to reset a foreach loop to re-iterate through the
collection as if it were starting from the beginning? Namely, if I
delete
an item out of a collection, I want to be able to reset the loop.


Hi Ken,

So far we have all discussed various work-arounds to this issue.
Now, I would like to suggest that you take a different approach.

I call it "The Hit List" or "Death Row" and it works like this

----------- Pseudocode -----------
ArrayList HitList = new HitList();
foreach (Thing thing in YourCollection)
{
if (NeedsKilling(thing))
{
HitList.Add(thing);
}
else
{
Process(thing);
}
}
foreach(Thing victim in HitList)
{
YourCollection.Remove(victim);
}
-------------------------------------
Advantages
------------
This algorithm is O(n) as opposed to the others which were O(n^2).
You only loop through the collection once so you can do other processing
as well.
------------

It would be nice to have something like remove_if() from the C++ STL.

Hope this helps
Bill

Nov 17 '05 #15

P: n/a
Here is another way to do it in one pass:

string[] sa = new string[]{"one", "one", "two", "one", "two",
"two", "three", "one"};
ArrayList al = new ArrayList(sa);
string sToDel = "one";
for ( int i = 0; i < al.Count; )
{
string s = (string)al[i];
if ( s == sToDel )
{
al.RemoveAt(i);
continue;
}
i++;
}
Console.WriteLine("List after removing item(s):");
foreach ( string s in al )
{
Console.WriteLine(s);
}

--
William Stacey [MVP]

"William Stacey [MVP]" <st***********@mvps.org> wrote in message
news:Ol****************@TK2MSFTNGP12.phx.gbl...
IIRC, Remove iterates the list too until it finds the object. So you
iterate once for the hitlist and one for item in the hitlist. I would
agree this is probably the best way however.

--
William Stacey [MVP]

"Bill Butler" <qw****@asdf.com> wrote in message
news:7JKue.6432$PZ6.4885@trndny08...
"Ken Varn" <nospam> wrote in message
news:up**************@TK2MSFTNGP14.phx.gbl...
Is there any way to reset a foreach loop to re-iterate through the
collection as if it were starting from the beginning? Namely, if I
delete
an item out of a collection, I want to be able to reset the loop.


Hi Ken,

So far we have all discussed various work-arounds to this issue.
Now, I would like to suggest that you take a different approach.

I call it "The Hit List" or "Death Row" and it works like this

----------- Pseudocode -----------
ArrayList HitList = new HitList();
foreach (Thing thing in YourCollection)
{
if (NeedsKilling(thing))
{
HitList.Add(thing);
}
else
{
Process(thing);
}
}
foreach(Thing victim in HitList)
{
YourCollection.Remove(victim);
}
-------------------------------------
Advantages
------------
This algorithm is O(n) as opposed to the others which were O(n^2).
You only loop through the collection once so you can do other processing
as well.
------------

It would be nice to have something like remove_if() from the C++ STL.

Hope this helps
Bill


Nov 17 '05 #16

P: n/a
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Personally I don't like do/while instead of just plain while:


Normallly, so do I. There, I was going for the least change to the
original.

--
--
Truth,
James Curran
[erstwhile VC++ MVP]

Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
Nov 17 '05 #17

P: n/a
"Maqsood Ahmed" <ma***********@gmail.com> wrote in message
news:#N**************@TK2MSFTNGP10.phx.gbl...
Hello,
As far as I know, if you try to remove an item inside the foreach an
exception will occur as the enumerator gets corrupted for the foreach
loop.


Deleting shouldn't cause the exception. Using the enumerator after a
deletion should. (i.e, you would need to exit the loop immedaitely after the
deletion)

--
--
Truth,
James Curran
[erstwhile VC++ MVP]

Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
Nov 17 '05 #18

P: n/a
FWIW:

If the order that you use to iterate the collection does not matter, you can
make it a little simpler by iterating the collection backwards:

string[] sa = new string[] {"one", "one", "two", "etc", "one", "etc"};
ArrayList al = new ArrayList(sa); // kind of contrived
string sToDel = "one";
for(int i = al.Count - 1; i >= 0; i--)
{
if(sToDel.Equals(al[i]))
al.RemoveAt(i);
}
since you are counting down, the deletion does not affect the index of your
next test.

"William Stacey [MVP]" <st***********@mvps.org> wrote in message
news:e4**************@tk2msftngp13.phx.gbl...
Here is another way to do it in one pass:

string[] sa = new string[]{"one", "one", "two", "one", "two",
"two", "three", "one"};
ArrayList al = new ArrayList(sa);
string sToDel = "one";
for ( int i = 0; i < al.Count; )
{
string s = (string)al[i];
if ( s == sToDel )
{
al.RemoveAt(i);
continue;
}
i++;
}
Console.WriteLine("List after removing item(s):");
foreach ( string s in al )
{
Console.WriteLine(s);
}

--
William Stacey [MVP]

"William Stacey [MVP]" <st***********@mvps.org> wrote in message
news:Ol****************@TK2MSFTNGP12.phx.gbl...
IIRC, Remove iterates the list too until it finds the object. So you
iterate once for the hitlist and one for item in the hitlist. I would
agree this is probably the best way however.

--
William Stacey [MVP]

"Bill Butler" <qw****@asdf.com> wrote in message
news:7JKue.6432$PZ6.4885@trndny08...
"Ken Varn" <nospam> wrote in message
news:up**************@TK2MSFTNGP14.phx.gbl...
Is there any way to reset a foreach loop to re-iterate through the
collection as if it were starting from the beginning? Namely, if I
delete
an item out of a collection, I want to be able to reset the loop.
Hi Ken,

So far we have all discussed various work-arounds to this issue.
Now, I would like to suggest that you take a different approach.

I call it "The Hit List" or "Death Row" and it works like this

----------- Pseudocode -----------
ArrayList HitList = new HitList();
foreach (Thing thing in YourCollection)
{
if (NeedsKilling(thing))
{
HitList.Add(thing);
}
else
{
Process(thing);
}
}
foreach(Thing victim in HitList)
{
YourCollection.Remove(victim);
}
-------------------------------------
Advantages
------------
This algorithm is O(n) as opposed to the others which were O(n^2).
You only loop through the collection once so you can do other processing
as well.
------------

It would be nice to have something like remove_if() from the C++ STL.

Hope this helps
Bill



Nov 17 '05 #19

This discussion thread is closed

Replies have been disabled for this discussion.