473,326 Members | 2,147 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Remove an item from an arraylist inside foreach

I have an ArrayList of thread pointers that I want delete from my list when
the Thread in not alive and status is stopped. But I want to do it from the
foreach loop I am looping through. threadList is the ArrayList.

foreach (Thread theThread in threadList)
{
if ((!theThread.IsAlive) && (theThread.ThreadState.ToString ==
"Stopped"))
sw.WriteLine(" Status for Thread: {0} is {1} IsAlive: {2}",
theThread.Name, theThread.ThreadState,theThread.IsAlive);

// this is where I want to take the pointer out of the list - something
like threadList.current.remove.
}

Thanks,

Tom
Jan 31 '08 #1
4 17669
Tom,

This fails because you can not change the list while iterating through
the list with foreach (i.e. accessing through IEnumerable).

To get around this, you should use a regular for construct, starting
with the last index in the list, and then cycling through and removing them
if appropriate (you start at the last item in the list because if you remove
one while moving forward, you have to readjust your index to account for the
shifting of the indexes of the remaining elements).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"tshad" <ts***@dslextreme.comwrote in message
news:eX**************@TK2MSFTNGP04.phx.gbl...
>I have an ArrayList of thread pointers that I want delete from my list when
the Thread in not alive and status is stopped. But I want to do it from
the foreach loop I am looping through. threadList is the ArrayList.

foreach (Thread theThread in threadList)
{
if ((!theThread.IsAlive) && (theThread.ThreadState.ToString ==
"Stopped"))
sw.WriteLine(" Status for Thread: {0} is {1} IsAlive: {2}",
theThread.Name, theThread.ThreadState,theThread.IsAlive);

// this is where I want to take the pointer out of the list - something
like threadList.current.remove.
}

Thanks,

Tom

Jan 31 '08 #2
You cannot. A collection cannot be modified while being enumerated.

Hi Ignacio,

Well, I am not sure if I would go as far as saying that. I may be wrong but
I think someone could create their own collection (implementing their own
IEnumerator) and on their implementation they don't have to throw an error
if the collection is modified while enumerating.

Now, I am not saying if that is a good idea to do or not, all I am saying is
that just because all .Net collection will throw an error if the collection
is modified while enumerating does not mean that *all* collection will do
the same thing.

I don't believe this behavior governed by the runtime. In other words,
people should not count on this behavior by default... but then again, I may
be wrong!!
Cheers.
Jan 31 '08 #3
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.comwrote in
message news:47**********************************@microsof t.com...
Tom,

This fails because you can not change the list while iterating through
the list with foreach (i.e. accessing through IEnumerable).

To get around this, you should use a regular for construct, starting
with the last index in the list, and then cycling through and removing
them if appropriate (you start at the last item in the list because if you
remove one while moving forward, you have to readjust your index to
account for the shifting of the indexes of the remaining elements).

That's as good a way as any.

Thanks,

Tom
>

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"tshad" <ts***@dslextreme.comwrote in message
news:eX**************@TK2MSFTNGP04.phx.gbl...
>>I have an ArrayList of thread pointers that I want delete from my list
when the Thread in not alive and status is stopped. But I want to do it
from the foreach loop I am looping through. threadList is the ArrayList.

foreach (Thread theThread in threadList)
{
if ((!theThread.IsAlive) && (theThread.ThreadState.ToString ==
"Stopped"))
sw.WriteLine(" Status for Thread: {0} is {1} IsAlive: {2}",
theThread.Name, theThread.ThreadState,theThread.IsAlive);

// this is where I want to take the pointer out of the list -
something like threadList.current.remove.
}

Thanks,

Tom


Feb 1 '08 #4
Aside; if this was List<Threadinstead of ArrayList, you could do
something like below (using C# 3 lambda syntax, but an anonymous
method would work just as well):

threadList.RemoveAll(thread ={
if ((!thread.IsAlive) &&
(thread.ThreadState.ToString() == "Stopped")) {
sw.WriteLine("...foo...");
return true;
}
return false;
});

Marc
Feb 1 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: K. Byanjankar | last post by:
Hi, is there a way to remove item from cookie collection that has a key to it... -- Response.cookies("items")("item1") = "111111" Response.cookies("items")("item2") = "222222"...
2
by: MFRASER | last post by:
How do I go about looping through a hash table and removing items. I know how do this in a collectionbase, but can't iterate through the hash table with out getting an error. Here is my sample...
2
by: James | last post by:
How would I skip an item in a foreach loop without breaking out of the loop altogether? foreach(SearchResult resCol1 in resCol) { string myString = resCol1.Properties.ToString(); if...
4
by: Jon Paal | last post by:
how can I search for a value in a multi - item arraylist to prevent adding duplicates ?
4
by: rjl | last post by:
Is there a way to assign an arraylist inside an arraylist as a column? i have arrayList list, which has 2 Strings and an arrayList with 3 values. I would like the following columns then in a...
2
by: Kela | last post by:
An interesting problem: I have a ListView with LabelEdit set to TRUE. When I change the label, I want to make some decisions as to whether the ListViewItem (that's just been edited) should stay in...
5
by: blisspikle | last post by:
I figure that someone good at dotnet can look at this and give me a clue on how to easily organize this code? If there is a unique identifier like "Publisher" with a bunch of "Book" that are...
10
by: =?Utf-8?B?YmJn?= | last post by:
Hi all, I wanted to go through each entry(?) of ArrayList and remove some particular entry. So I tried following but it throws exception at runtime: foreach (myEntry entry in myArrayList) {...
8
by: Andrus | last post by:
Code below causes error in class definition line .....Isolator<T>' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. 'Myapp.Isolator<T>.GetEnumerator()'...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.