Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add keys/values to Dictionary at declaration

Very easy today, I think. In C#, its:

Dictionary<String, String> dict = new Dictionary<string, string>() { { "", "" } }; 

But in vb, the following doesn't work.

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) (("","")) 

I'm pretty sure there's a way to add them at declaration, but I'm not sure how. And yes, I want to add them at declaration, not any other time. :) So hopefully it's possible. Thanks everyone.

I've also tried:

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) ({"",""}) 

And...

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) {("","")} 

And...

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) {{"",""}} 
like image 606
XstreamINsanity Avatar asked Sep 22 '10 17:09

XstreamINsanity


People also ask

How do you add a value to an existing key in a dictionary?

We can add / append new key-value pairs to a dictionary using update() function and [] operator. We can also append new values to existing values for a key or replace the values of existing keys using the same subscript operator and update() function.

Can you add new keys to a dictionary?

You can add key to dictionary in python using mydict["newkey"] = "newValue" method. Dictionaries are changeable, ordered, and don't allow duplicate keys. However, different keys can have the same value.

How do I add data to a dictionary in Python?

Method 1: Using += sign on a key with an empty value In this method, we will use the += operator to append a list into the dictionary, for this we will take a dictionary and then add elements as a list into the dictionary.


1 Answers

This is possible in VB.NET 10:

Dim dict = New Dictionary(Of Integer, String) From {{ 1, "Test1" }, { 2, "Test1" }} 

Unfortunately IIRC VS 2008 uses VB.NET 9 compiler which doesn't support this syntax.

And for those that might be interested here's what happens behind the scenes (C#):

Dictionary<int, string> VB$t_ref$S0 = new Dictionary<int, string>(); VB$t_ref$S0.Add(1, "Test1"); VB$t_ref$S0.Add(2, "Test1"); Dictionary<int, string> dict = VB$t_ref$S0; 
like image 140
Darin Dimitrov Avatar answered Nov 27 '22 08:11

Darin Dimitrov