How to insert values โ€‹โ€‹into a VB.NET dictionary when creating an instance?

Is there a way I can insert values โ€‹โ€‹into a VB.NET dictionary when creating it? I can, but do not want to, do dict.Add (int, "string") for each element.

Basically, I want to do "How to insert values โ€‹โ€‹into a C # dictionary when creating an instance?" using VB.NET.

var dictionary = new Dictionary<int, string> { {0, "string"}, {1, "string2"}, {2, "string3"} }; 
+45
Nov 03 '09 at 0:12
source share
3 answers

When using Visual Studio 2010 or later, you should use the FROM keyword as follows:

 Dim days = New Dictionary(Of Integer, String) From {{0, "string"}, {1, "string2"}} 

See: http://msdn.microsoft.com/en-us/library/dd293617(VS.100).aspx

If you need to use a previous version of Visual Studio, and you need to do this often, you can simply inherit the dictionary class and implement it yourself.

It might look something like this:

 Public Class InitializableDictionary Inherits Dictionary(Of Int32, String) Public Sub New(ByVal args() As KeyValuePair(Of Int32, String)) MyBase.New() For Each kvp As KeyValuePair(Of Int32, String) In args Me.Add(kvp.Key, kvp.Value) Next End Sub End Class 
+53
Nov 03 '09 at 0:18
source share

These are not possible versions of Visual Basic until 2010.

In VB2010 and later, you can use the FROM keyword.

 Dim days = New Dictionary(Of Integer, String) From {{0, "Sunday"}, {1, "Monday"}} 

Link

http://msdn.microsoft.com/en-us/library/dd293617(VS.100).aspx

+25
Nov 03 '09 at 0:45
source share

What you are looking at is a C # function called "collection initializers." This feature existed for VB, but it was cut before the release of Visual Studio 2008. It will not help you right now, but it is expected to be available in Visual Studio 2010. At the same time, you will have to do it in the old-fashioned way; call the .Add() method of your new instance.

+5
Nov 03 '09 at 0:40
source share



All Articles