Copying a stringdictionary

duggold
10 Jun 2012, 18:40
I am enumerating through a stringdictionary using foreach. The problem is, when I process each item I may remove or add items to the stringdictionary. So, when I run it, it errors telling me the list has been changed and the enumeration may not work. So, I tried an assign:

new_list = old_list

and enumerate the new_list. Unfortunately, it appears the assignment didn't copy the data but just pointed my variable to the same list so the enumeration still fails.

As a workaround, I make a new stringdictionary and one by one use dictionary add to fill it with the contents of the first list. Then, enumerate the new list. But, this is rather ugly and uses CPU time. Is there a way to force an assignment to do an actual copy rather then a reference?

sgreig
11 Jun 2012, 00:44
EDIT

Scrap that. I have a function in one of my games that makes copies of lists specifically to deal with that problem.


<function name="ObjectListCopy" parameters="source" type="objectlist">
result = NewObjectList()
foreach (item, source) {
list add (result, item)
}
return (result)
</function>


You would change result = NewObjectList() to result = NewStringList() for your purpose, but it should work.

duggold
11 Jun 2012, 02:33
Yes, I did end up putting in the copy code myself, but I felt that was pretty inefficient and thought, like other languages, there would be a copy other then by reference. Oh well...

Pertex
11 Jun 2012, 08:51
I think you could do something like this


newlist = NewObjectList()
newlist = ListCombine ( null , yourlist )

sgreig
11 Jun 2012, 09:06
That's originally what I was going to suggest Pertex. However, my game Sleuth makes extensive use of that list copying function and it has absolutely no discernible effect on performance. I can't take the credit for writing it though, as much as I'd like to. It was Alex who came up with it. :)