63

Is there a way that I can insert values into a VB.NET Dictionary when I create it? I can, but don't want to, do dict.Add(int, "string") for each item.

Basically, I want to do "How to insert values into C# Dictionary on instantiation?" with VB.NET.

var dictionary = new Dictionary<int, string>
    {
        {0, "string"},
        {1, "string2"},
        {2, "string3"}
    };
Community
  • 1
  • 1
onsaito
  • 793
  • 1
  • 6
  • 7

3 Answers3

80

If using Visual Studio 2010 or later you should use the FROM keyword like this:

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 prior version of Visual Studio and you need to do this frequently you could just inherit from 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
brendan
  • 29,308
  • 20
  • 68
  • 109
28

This is not possible versions of Visual Basic prior to 2010.

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

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

Reference

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

Brian Webster
  • 30,033
  • 48
  • 152
  • 225
Stefan
  • 11,423
  • 8
  • 50
  • 75
  • As Joel Coehoorn says in his answer, it seems like the FROM keyword has been pulled out of VB2008. I strongly remember I have used this before, but maybe I only tried Array-inizializers. Well. Here are the link I got my information from anyway: http://msdn.microsoft.com/en-us/library/dd293617(VS.100).aspx – Stefan Nov 03 '09 at 01:00
5

What you're looking at is a feature of C# called "collection initializers". The feature existed for VB as well, but was cut prior to the release of Visual Studio 2008. It doesn't help you right now, but this is expected to be available in Visual Studio 2010. In the meantime, you'll have to do it the old fashioned way — call the .Add() method of your new instance.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794