anshu
anshu

Reputation: 159

Compile error while adding items to nested dictionary

I am trying to created nested dictionary variable like the below, But I get compile error stating that it needs "}" at line where I am adding items (line #2) to my nested dictionary.

What Am I missing here? Thanks.

Dim myNestedDictionary As Dictionary(Of String, Dictionary(Of String, Integer)) = New Dictionary(Of String, Dictionary(Of String, Integer))()


myNestedDictionary.Add("A", New Dictionary("A", 4)())

Upvotes: 1

Views: 1469

Answers (3)

Ando
Ando

Reputation: 11409

In VS 2008 and .net 3.5 you cannot declare and initialize a Dictionary in one line, so you have to do:

 Dim myNestedDictionary As New Dictionary(Of String, Dictionary(Of String, Integer))()
 Dim lTempDict As New Dictionary(Of String, Integer)
 lTempDict.Add("A", 4)
 myNestedDictionary.Add("A", lTempDict)

To retrieve the an item use the following:

Dim lDictionaryForA As Dictionary(Of String, Integer) = myNestedDictionary.Item("A")
Dim lValueForA As Integer = lDictionaryForA.Item("A")

The value in lValueForA should be 4.

Upvotes: 1

Richard Anthony Hein
Richard Anthony Hein

Reputation: 10650

In C# you can do that:

var myNestedDictionary = new Dictionary<string, Dictionary<string, int>>() {{ "A", new Dictionary<string, int>() { { "A", 4 } } }};

You can do it in VB 2010 as well, using the From keyword, but it doesn't compile in VS 2008. It will compile in VB 2010, no matter which .NET Framework you target. I've tried 2.0, 3.5 and 4.0.

Dim myNestedDictionary = New Dictionary(Of String, Dictionary(Of String, Integer))() From {{"A", New Dictionary(Of String, Integer) From {{"A", 4}}}}

Upvotes: 1

M.A. Hanin
M.A. Hanin

Reputation: 8074

You need to specify the type of dictionary you are creating when you add the records:

myNestedDictionary.Add("A", New Dictionary(Of String, Integer))

or otherwise pass an existing Dictionary(Of String, Integer) as the inside-dictionary argument (when adding key/value pairs to the external dictionary).

(BTW, Your external dictionary is a dictionary who's Keys are Strings and Values are Dictionaries (Of String, Integer), is this really what you wanted?)

Upvotes: 1

Related Questions