473,761 Members | 9,284 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 34161
"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
3415
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
1540
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
2353
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
43556
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
1722
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
1518
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
1595
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
2843
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
3748
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
11139
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
9376
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10136
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
9988
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
9923
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,...
1
7358
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
6640
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
5266
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
3911
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
3509
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.