473,671 Members | 2,422 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Remove Values From Dictionary while Looping Through Values

I need the ability to parse through the values of a Dictionary and
remove certain ones depending on their attribute values. In the example
below, an InvalidOperatio nException is thrown in the foreach statement
when the first item is removed from the Dictionary.

From looking at Dictionary's methods, I couldn't find anything to
create a copy of the Values before starting the foreach loop. Help?
static void someTest() {
Dictionary<Stri ng, Int32storage = new Dictionary<stri ng, Int32>();
for (int i = 0; i < 100; i++) {
String bar = "Test" + i;
Int32 foo = new Int32();
foo = i;
storage.Add(bar , foo);
}
foreach (Int32 tmp in storage.Values) {
if ((tmp % 5) == 0) {
String bar = "Test" + tmp;
storage.Remove( bar);
}
}
}
Nov 1 '06 #1
4 34151
"O.B." <fu******@bells outh.neta écrit dans le message de news:
12************* @corp.supernews .com...

|I need the ability to parse through the values of a Dictionary and
| remove certain ones depending on their attribute values. In the example
| below, an InvalidOperatio nException is thrown in the foreach statement
| when the first item is removed from the Dictionary.

You cannot modify any list that is running an enumerator of iterator. You
need to use :

for (int i = list.count - 1; i >= 0; i--)
...

to ensure that items removed do not upset the iteration.

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Nov 2 '06 #2
"O.B." <fu******@bells outh.netwrote in message
news:12******** *****@corp.supe rnews.com...
>I need the ability to parse through the values of a Dictionary and remove
certain ones depending on their attribute values. In the example below, an
InvalidOperati onException is thrown in the foreach statement when the first
item is removed from the Dictionary.

From looking at Dictionary's methods, I couldn't find anything to create a
copy of the Values before starting the foreach loop. Help?
You cannot modify a container without invalidating all active enumerators -
hence breaking your foreach statement. For a dictionary, what you need to
do is to build a list of keys to be deleted, then use a second loop through
that list to remove items from the dictionary.

static void someTest() {
Dictionary<Stri ng, Int32storage = new Dictionary<stri ng, Int32>();
for (int i = 0; i < 100; i++) {
String bar = "Test" + i;
Int32 foo = new Int32();
foo = i;
storage.Add(bar , foo);
}

List<stringkeys ToDelete = new List<string>();
foreach (Int32 tmp in storage.Values) {
if ((tmp % 5) == 0) {
String bar = "Test" + tmp;
keysToDelete.Ad d(bar);
}
}
foreach (string key in keysToDelete) {
storage.Remove( key);
}
}

-cd
Nov 2 '06 #3
Carl Daniel [VC++ MVP] wrote:
"O.B." <fu******@bells outh.netwrote in message
news:12******** *****@corp.supe rnews.com...
>I need the ability to parse through the values of a Dictionary and remove
certain ones depending on their attribute values. In the example below, an
InvalidOperati onException is thrown in the foreach statement when the first
item is removed from the Dictionary.

From looking at Dictionary's methods, I couldn't find anything to create a
copy of the Values before starting the foreach loop. Help?

You cannot modify a container without invalidating all active enumerators -
hence breaking your foreach statement. For a dictionary, what you need to
do is to build a list of keys to be deleted, then use a second loop through
that list to remove items from the dictionary.

static void someTest() {
Dictionary<Stri ng, Int32storage = new Dictionary<stri ng, Int32>();
for (int i = 0; i < 100; i++) {
String bar = "Test" + i;
Int32 foo = new Int32();
foo = i;
storage.Add(bar , foo);
}

List<stringkeys ToDelete = new List<string>();
foreach (Int32 tmp in storage.Values) {
if ((tmp % 5) == 0) {
String bar = "Test" + tmp;
keysToDelete.Ad d(bar);
}
}
foreach (string key in keysToDelete) {
storage.Remove( key);
}
}
This got me going in the right direction. The following is a little
more compact:

Given entityDatase as a Dictionary<long , MyClass>:

MyClass[] tempList = new MyClass[entityDatabase. Count];
entityDatabase. Values.CopyTo(t empList, 0);

foreach (MyClass tmp in tempList) {
if (tmp.invalid) {
entityDatabase. Remove(tmp);
}
}
Nov 3 '06 #4

O.B. wrote:
Carl Daniel [VC++ MVP] wrote:
"O.B." <fu******@bells outh.netwrote in message
news:12******** *****@corp.supe rnews.com...
I need the ability to parse through the values of a Dictionary and remove
certain ones depending on their attribute values. In the example below, an
InvalidOperatio nException is thrown in the foreach statement when the first
item is removed from the Dictionary.

From looking at Dictionary's methods, I couldn't find anything to create a
copy of the Values before starting the foreach loop. Help?
You cannot modify a container without invalidating all active enumerators -
hence breaking your foreach statement. For a dictionary, what you need to
do is to build a list of keys to be deleted, then use a second loop through
that list to remove items from the dictionary.

static void someTest() {
Dictionary<Stri ng, Int32storage = new Dictionary<stri ng, Int32>();
for (int i = 0; i < 100; i++) {
String bar = "Test" + i;
Int32 foo = new Int32();
foo = i;
storage.Add(bar , foo);
}

List<stringkeys ToDelete = new List<string>();
foreach (Int32 tmp in storage.Values) {
if ((tmp % 5) == 0) {
String bar = "Test" + tmp;
keysToDelete.Ad d(bar);
}
}
foreach (string key in keysToDelete) {
storage.Remove( key);
}
}

This got me going in the right direction. The following is a little
more compact:

Given entityDatase as a Dictionary<long , MyClass>:

MyClass[] tempList = new MyClass[entityDatabase. Count];
entityDatabase. Values.CopyTo(t empList, 0);

foreach (MyClass tmp in tempList) {
if (tmp.invalid) {
entityDatabase. Remove(tmp);
}
}
Well, yes, it's more compact, but it ends up copying a lot more
information than it has to. Carl's solution is one of the two
"standard" solutions to this problem, the other one given by Joanna is
iterating through a list in reverse. For the case of a Dictionary I
would choose Carl's method.

Nov 3 '06 #5

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

Similar topics

3
3407
by: babu | last post by:
Hello All, How are you? I am facing an issue to print all the form control values (including datagrid values). Is there a way to print all the control values in VB.NET. If the grid contains more rows of data (like
2
1531
by: robbiehenry | last post by:
I built my company's website and the content portion of the site uses text with styles with relative values and the navigational part of the site uses text with styles with absolute values. The purpose of this was so that the end user could increase the size of the text on the webpage and only the content portion of the page would scale or resize but the navigation would not. This works as expected on a pc but the entire page scales on a...
7
2351
by: Carl | last post by:
Hi I have a form that requires the user to enter a tenancy reference number in the first column, and when this is done it brings back their direct debit payment for their rent in the second column (It uses SQl to bring back the amount when the Tenancy Reference No loses the focus). In a third column I want the user to type in the value for the new rent amount. This may be for one tenancy record up to 25 in one go, for example: Tenancy...
5
43542
by: Martin Pöpping | last post by:
Hello, I´ve a simple question about existing data structures/ collections. Is there a way to sort a dictionary (or any comparable collection/ data structure) by values instead of by keys? For example if you have a dictionary with words as keys and the frequency of these words in a text as values.
2
1719
ak1dnar
by: ak1dnar | last post by:
CREATE TABLE `products` ( `p_id` int(11) NOT NULL, `p_name` varchar(15) default NULL, `p_features` varchar(100) default NULL ) from this table I am going to fetch the records and display it. But there is a problem i have to display Product features as Bulleted lines. Please consider this sample value:
2
1514
by: programming | last post by:
I just would like to re-explain the problem i am having as i had not received any posts, so i might of explained in poorly. The problem i am having is NOT parse error related, more or less a problem in my logic. Ok , well what is happening is i am getting my values in member.txt fields ok from reading it, but when i attempted to write those values back to the member.txt file with updated string values, my member.txt file is cleared of...
4
1590
by: psbasha | last post by:
Hi , The below snippet of the code is returing the empty dict,but I would like to get the values in the dict as {1:200,2:300,3:400}. Could anybody suggest what method I have to use to return the dict values as function argument. Sample.py class Sample: def __init__(self):
2
2838
by: kdt | last post by:
Hi, I need to perform some horrible functions in python I need to do, using sort in a similar way that Excel can. With a dictionary like: >>> d {8: (99, 99), 9: , 4: , 5: (67, 77)} I want to sort the entire dictionary based on the last values in each line. First for and then.
4
3739
by: Chronictank | last post by:
Hi, as a bit of background (and seeing as it is my first post :)) i am a complete newbie at perl. I literally picked it up a week ago to do this project as it seemed like the best choice for a language to connect to a SQL database in a Unix envirment as well as script parsing so there is more than likely a ton of things i could have done a better way. I have been at this for 3 days now and cant for the life of me work out why the code is...
4
11136
by: Atrisa | last post by:
Hi everyone. I have a file of records like this: ID:13 Date: 12.12 Scores: 2 ID:22 Date: 9.12 Scores: 4
0
8926
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
8824
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...
0
7444
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
6236
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
4227
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
4416
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2818
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
2
2060
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1815
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.