473,624 Members | 2,119 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

delete element of collection being iterated

Hello.

Sometimes I encounter the following problem:

foreach( element of some collection)
{
delete this element;
}

of course, the runtime would not allow to modify
the collection whilst executing loop through
its elements.

I often happen to write solutoin to this problem
by myself, but i am curious if there is some
design pattern how to handle such a situation
(the need to delete element of collection being ierated
through)

Thaks for answer
Michal Januszczyk
Nov 22 '05 #1
3 1638
One trick is to use "for(){}" backward, insteadof "foreach(){ }":

for (int i=myCollection. Count-1; i>=0; i--)
{
myCollection.Re moveAt(i)
//Or your own Delete(i)/Remove(i) method, because if you remove item
//from a collection backward, remaining item's index will not change
}

"Michal Januszczyk" <an*******@disc ussions.microso ft.com> wrote in message
news:03******** *************** *****@phx.gbl.. .
Hello.

Sometimes I encounter the following problem:

foreach( element of some collection)
{
delete this element;
}

of course, the runtime would not allow to modify
the collection whilst executing loop through
its elements.

I often happen to write solutoin to this problem
by myself, but i am curious if there is some
design pattern how to handle such a situation
(the need to delete element of collection being ierated
through)

Thaks for answer
Michal Januszczyk

Nov 22 '05 #2
Hi,

I also faced this problem and incorporated the following
solution for the same.

// Create a Hashtable and clone the existing HashTable
(accessible through the InnerHashtable property of the
types derived from the DictionaryBase class).

System.Collecti ons.Hashtable LocalHashTable =
(System.Collect ions.Hashtable) this.InnerHasht able.Clone();

// Create an IEnumerator type instance, so as to traverse
the collection.

System.Collecti ons.IEnumerator KeysEnumerator =
LocalHashTable. GetEnumerator() ;

// Finally traverse the collection
while (KeysEnumerator .MoveNext())
{
// Now you can manipulate the collection.
this.Dictionary .Remove(OldCell Key);
}

Regards,
Puneet Taneja

-----Original Message-----
One trick is to use "for(){}" backward, insteadof "foreach(){ }":
for (int i=myCollection. Count-1; i>=0; i--)
{
myCollection.Re moveAt(i)
//Or your own Delete(i)/Remove(i) method, because if you remove item //from a collection backward, remaining item's index will not change}

"Michal Januszczyk" <an*******@disc ussions.microso ft.com> wrote in messagenews:03******* *************** ******@phx.gbl. ..
Hello.

Sometimes I encounter the following problem:

foreach( element of some collection)
{
delete this element;
}

of course, the runtime would not allow to modify
the collection whilst executing loop through
its elements.

I often happen to write solutoin to this problem
by myself, but i am curious if there is some
design pattern how to handle such a situation
(the need to delete element of collection being ierated
through)

Thaks for answer
Michal Januszczyk

.

Nov 22 '05 #3
If you create the iterator against a clone of the collection, you can delete from the original collection while continuing to iterate the clone

"
Private ie as IEnumerator = MyList.Clone.Ge tEnumerator()
"

From http://www.developmentnow.com/g/34_2...g-iterated.htm

Posted via DevelopmentNow. com Groups
http://www.developmentnow.com
Sep 8 '06 #4

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

Similar topics

2
331
by: Michal Januszczyk | last post by:
Hello. Sometimes I encounter the following problem: foreach( element of some collection) { delete this element; } of course, the runtime would not allow to modify
3
7969
by: Grandma Wilkerson | last post by:
Hi, The documentation states that enumeration through a collection is inherently NOT thread-safe, since a thread which added/removed an item from said collection could screw up the thread that was iterating. That makes sense.. but... given a collection that is filled at start-time and never modified again, is it safe to have multiple threads *reading* (not writing to) the collection using foreach()? I have a class that exposes an...
7
1884
by: Marc Bishop | last post by:
Hi can anyone help? I'm making a shopping cart and am stuck on removing an item from my array? The array is made : cArray(ITEM_NAME,cItem) = ProductName
3
7586
by: Jeff L. | last post by:
I have an interesting problem and I'm not coming up with any answers in my searches, so hopefully someone can give me a hand with this. I have a feeling it's easy, but I usually get my nose stuck too far in the details to see the big picture. :) I want to create a collection of key/value pairs. I have a class for the key/value pair...we'll just call it KeyValuePair for this example. Now, when creating the collection, I need to be...
13
14719
by: Joseph Garvin | last post by:
When I first came to Python I did a lot of C style loops like this: for i in range(len(myarray)): print myarray Obviously the more pythonic way is: for i in my array: print i
10
12197
by: | last post by:
I'm fairly new to ASP and must admit its proving a lot more unnecessarily complicated than the other languages I know. I feel this is because there aren't many good official resources out there to help do the most basic things. One of the "basic" things I haven't been able to find out how to do is how to delete an item from a multidimensional array object and resize it afterwards. It seems so easy to conceive of the code to delete...
4
2768
by: Kyote | last post by:
I'm trying to persist a list of filenames. I've made a custom collection and a FileName class: 'Class to hold file name information Public Class FileNames Public fullName As String Public fileName As String Public fileExtention As String Public filePath As String Public newName As String
11
2932
by: shiniskumar | last post by:
Ive got a collection with values Object= hashmap(k,v) Object= hashmap(k,v) Object= hashmap(k,v) Object= hashmap(k,v) Object= hashmap(k,v) i terated this collection and deleted object. then when i iterate again i get the following exception. java.util.ConcurrentModificationException
1
1728
by: shiniskumar | last post by:
how to delete the last element of a collection without iterating it?
0
8677
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...
1
8335
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
8474
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
7158
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...
1
6110
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5563
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4079
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...
1
1784
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1482
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.