2

I've got a nested dict like:

 Public collectionMain As New Dictionary(Of String, Dictionary(Of String, String))

When inserting a new item:

collectionMain.Add(node.SelectSingleNode("key").InnerText.Trim, collectionSub)
collectionSub.Clear()

On the add my collectionSub is filled with key & values. But when calling clear, the collectionMain.value is empty.

How can i keep the collectionMain dictionary value?

The collectionSub needs to be cleared, it's in a loop for filling.

thank you

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
TomVD
  • 109
  • 2
  • 13

3 Answers3

3

You need to create a New Dictionary(Of String, String) for each value.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • How do you mean? create a NEW collectionSub for every dictionary that i need in the collectionmain value? It's in a loop, and I don't know how many collectionSubs I need. – TomVD Dec 28 '11 at 14:32
  • @TomVD: Create a `New Dictionary(Of String, String)()` inside the loop. – SLaks Dec 28 '11 at 14:39
1

Whenever you add a new dictionary item, you will have to declare a new sub-dictionary for that key:

collectionMain.Add(node.SelectSingleNode("key").InnerText.Trim, _
                   New Dictionary(Of String, String))

The collectionSub variable really should not exist since every key in collectionMain has it's own dictionary.

LarsTech
  • 80,625
  • 14
  • 153
  • 225
1

Do not clear collectionSub. Don't forget that you are adding reference of Dictionary(Of String, String) - collectionSub. If you want to clear that object then you must have to create a "clone" (deep copy) of collectionSub. Take a look at SO thread - What is the best way to clone/deep copy a .NET generic Dictionary?

Community
  • 1
  • 1
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186