Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way of creating an associative array in VB.NET?

Tags:

vb.net

I'm a PHP guy, and in PHP I would do something like the following:

$variable = array('0001'=>'value1', '0010'=>'value2');

I'm pretty new to VB.NET, so how do I translate the above code to VB.NET?

I think I have to use a dictionary:

Dim variable As New Dictionary(Of String, String)
variable.Add("0001", "value1")
variable.Add("0010", "value2")

Is this the correct way of doing it or should I use something else for this?

like image 826
PeeHaa Avatar asked Aug 18 '11 18:08

PeeHaa


2 Answers

It is a way, or if you prefer a one-liner way of initialization, you can do this:

Dim variable As New Dictionary(Of String, String) From { {"0001", "value1"}, {"0010", "value2"} }

As far as which is the better one, it's more a matter of coding standard, and/or personal preference.

Considering what kind of container to use, you should use only those from System.Collection.Generics in .NET unless you are forced otherwise. And Dictionary is the default associative container. You can see the alternatives (SortedDictionary for example), if it matches more your use case.

like image 191
Matthieu Avatar answered Oct 17 '22 02:10

Matthieu


You can use Collection:

Dim var As New Collection
var.Add("vakue1", "0001")
var.Add("value2", "0010")

Loop through all with:

For Each v As String In var

Next

For other ways of treating items, look at the sample in Collection(Of T) Class (MSDN).

like image 1
Martin Avatar answered Oct 17 '22 02:10

Martin