Search code examples
vb.netsorteddictionary

Iterate over a changing SortedDictionary


Utility code I do not have access to is adding rows to the SortedDictionary(of Integer, RowData) I am trying to iterate over. It is adding new RowData's to the end of the list.

So I think the proper solution is to make a copy of the SortedDictionary, and then loop over it. I don't have to worry about sync problems because the new additions are always after the end.

But how to do this? I can't figure out the syntax, the documentation at MS is, hmmm, "basic", and the API doesn't make any sense whatsoever to me. What I want is a copy of the SortedDictionary making another SortedDictionary. But what I get is some sort of KeyValuePair array that I can't seem to make head nor tails of.

Dim TempR as KeyValuePair(Of Integer, RowData)
pRowDatas.CopyTo(TempR, 0)

That one tells me it can't copy it because one or the other is a 1-dimensional array and the other isn't. So I tried

Dim TempR() as KeyValuePair(Of Integer, RowData)
pRowDatas.CopyTo(TempR, 0)

And then it complained TempR was null. But you can't New it, or at least I can't.

What am I doing wrong here? Is there an easy way to do this?


Solution

  • In your example code, you need to initialize the array to the size of pRowDatas:

    Dim TempR(0 To pRowDatas.Count-1) As KeyValuePair(Of Integer, RowData)
    pRowDatas.CopyTo(TempR, 0)
    

    There's also a ToArray extension method that you could use:

    Dim TempR As KeyValuePair(Of Integer, RowData) = pRowDatas.ToArray()
    

    Neither of these are inherently thread-safe. The proper way to do this would be to implement a lock both here and in the utility code. Since you have no access to the code, it seems your options are limited here, but someone else may have some idea.