473,738 Members | 5,084 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Is Alive) && (theThread.Thre adState.ToStrin g ==
"Stopped"))
sw.WriteLine(" Status for Thread: {0} is {1} IsAlive: {2}",
theThread.Name, theThread.Threa dState,theThrea d.IsAlive);

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

Thanks,

Tom
Jan 31 '08 #1
4 17689
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.co m

"tshad" <ts***@dslextre me.comwrote in message
news:eX******** ******@TK2MSFTN GP04.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.Is Alive) && (theThread.Thre adState.ToStrin g ==
"Stopped"))
sw.WriteLine(" Status for Thread: {0} is {1} IsAlive: {2}",
theThread.Name, theThread.Threa dState,theThrea d.IsAlive);

// this is where I want to take the pointer out of the list - something
like threadList.curr ent.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.c omwrote in
message news:47******** *************** ***********@mic rosoft.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.co m

"tshad" <ts***@dslextre me.comwrote in message
news:eX******** ******@TK2MSFTN GP04.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.Is Alive) && (theThread.Thre adState.ToStrin g ==
"Stopped"))
sw.WriteLine(" Status for Thread: {0} is {1} IsAlive: {2}",
theThread.Name , theThread.Threa dState,theThrea d.IsAlive);

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

Thanks,

Tom


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

threadList.Remo veAll(thread ={
if ((!thread.IsAli ve) &&
(thread.ThreadS tate.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
1811
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" Response.cookies("items")("item3") = "333333" Is there a way I can remove items- item2 and rearrange above cookie into Response.cookies("items")("item1") = "111111"
2
24636
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 code for a collection base for(int i = this.Values.Count; i > 0 ; i--) { //Set local object
2
21252
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 (myString.IndexOf("badstuff") > 0) //go to next item … }
4
1520
by: Jon Paal | last post by:
how can I search for a value in a multi - item arraylist to prevent adding duplicates ?
4
4778
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 datagrid or gridview: string1, string2, (these next 3 in arrayList) listHeader1, listHeader2, listHeader3 thanks for any help.
2
3939
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 the ListView or not. The natural place to inspect this is in the AfterLabelEdit event... If the decision is to take the item out, I used the ListViewItem.Remove(). However - check this out: A) say that the item's index is N (indices are...
5
1472
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 published under them (I used the arraylist class in the publisher class). How should the code be organized, and how can the books properties like "Name" be easily called in the main code, or searched for in the main code?
10
18077
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) { // do something... if (entry.fieldA == 0)
8
2536
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()' cannot implement 'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.IEnumerator'. I tried to change method signature to
0
9473
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9334
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9259
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9208
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8208
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4569
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4824
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3279
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
3
2193
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.