472,973 Members | 2,340 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

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 InvalidOperationException 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<String, Int32storage = new Dictionary<string, 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 34090
"O.B." <fu******@bellsouth.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 InvalidOperationException 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******@bellsouth.netwrote in message
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
InvalidOperationException 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<String, Int32storage = new Dictionary<string, Int32>();
for (int i = 0; i < 100; i++) {
String bar = "Test" + i;
Int32 foo = new Int32();
foo = i;
storage.Add(bar, foo);
}

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

-cd
Nov 2 '06 #3
Carl Daniel [VC++ MVP] wrote:
"O.B." <fu******@bellsouth.netwrote in message
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
InvalidOperationException 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<String, Int32storage = new Dictionary<string, Int32>();
for (int i = 0; i < 100; i++) {
String bar = "Test" + i;
Int32 foo = new Int32();
foo = i;
storage.Add(bar, foo);
}

List<stringkeysToDelete = new List<string>();
foreach (Int32 tmp in storage.Values) {
if ((tmp % 5) == 0) {
String bar = "Test" + tmp;
keysToDelete.Add(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(tempList, 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******@bellsouth.netwrote in message
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
InvalidOperationException 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<String, Int32storage = new Dictionary<string, Int32>();
for (int i = 0; i < 100; i++) {
String bar = "Test" + i;
Int32 foo = new Int32();
foo = i;
storage.Add(bar, foo);
}

List<stringkeysToDelete = new List<string>();
foreach (Int32 tmp in storage.Values) {
if ((tmp % 5) == 0) {
String bar = "Test" + tmp;
keysToDelete.Add(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(tempList, 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
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...
2
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...
7
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...
5
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? ...
2
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...
2
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...
4
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...
2
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...
4
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...
4
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
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
3
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.