473,516 Members | 2,771 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reset a foreach loop.

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
18 6595
"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
"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
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
"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
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
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
> 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
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

"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
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
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
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
"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
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
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
"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
"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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
4284
by: Randell D. | last post by:
Folks, Ever since reading an interesting article in Linux Format on PHP whereby suggested code writing was made that could enhance performance on a server, I've started testing various bits of code everytime I found more than one method to perform a single task. I timed each method to find which would complete faster. I thought I'd share my...
2
2019
by: Pavils Jurjans | last post by:
Hello, please consider the code at the end of this posting, that depicts simple case of custom enumerator. This particular example will enumerate over list of random number within 1..10, and will stop once the value of 10 is reached. My question, is what's the real point of implemending the Reset() method, if it is never used by foreach...
104
7048
by: cody | last post by:
What about an enhancement of foreach loops which allows a syntax like that: foeach(int i in 1..10) { } // forward foeach(int i in 99..2) { } // backwards foeach(char c in 'a'..'z') { } // chars foeach(Color c in Red..Blue) { } // using enums It should work with all integral datatypes. Maybe we can step a bit further: foeach(int i in...
32
6471
by: Joe Rattz | last post by:
Hmmm, I wrote the following code. I want an array of bools and I want to intialize them to false. bool bits = new bool; foreach(bool bit in bits) { bit = false; } The compiler complains on the "bit = false;" stating that bit is read-only.
15
2657
by: Mike Lansdaal | last post by:
I came across a reference on a web site (http://www.personalmicrocosms.com/html/dotnettips.html#richtextbox_lines ) that said to speed up access to a rich text box's lines that you needed to use a "foreach" loop instead of a "for" loop. This made absolutely no sense to me, but the author had posted his code and timing results. The "foreach"...
3
33332
by: Akira | last post by:
I noticed that using foreach is much slower than using for-loop, so I want to change our current code from foreach to for-loop. But I can't figure out how. Could someone help me please? Current code is here: foreach ( string propertyName in ht.Keys ) { this.setProperty( propertyName, ht );
29
4202
by: Jon Slaughter | last post by:
Is it safe to remove elements from an array that foreach is working on? (normally this is not the case but not sure in php) If so is there an efficient way to handle it? (I could add the indexes to a temp array and delete afterwards if necessary but since I'm actually working in a nested situation this could get a little messy. I guess I could...
2
3216
by: recordlovelife | last post by:
So I am trying to display a title, date, and content of a wordpress blog. Word press provides nice drop in functions to get the job done with simple names like "the_title", and the "the_content" But on the homepage of a site, i wanted to truncate the content to like the first 75 characters and then put "..." (a perfect use of the smarty "truncate"...
7
2259
by: Osiris | last post by:
Just something I would like to share: I just learned the hard way (2 days detective work on a bug) that foreach loops are not at all like for loops, not intuitive at all. BEWARE: arrays and matrices are sparse by design/definition in PHP. I'm doing some matrix manipulation in a Finite Element program. Translating Fortran to PHP, because...
0
7276
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7408
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7548
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5110
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4773
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3259
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1624
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
825
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
488
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.