views:

532

answers:

3

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"}
    };
+1  A: 

I do not believe this is currently possible in VB.Net. If 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 IntializableDictionary
    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
That works. Thanks,
onsaito
+1  A: 
Joel Coehoorn
+2  A: 

If you are using Visual Basic 2008 you could use the FROM keyword:

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

EDIT: This will only work in Visual Basic 2010 as it was pulled from the VB2008.

http://msdn.microsoft.com/en-us/library/dd293617%28VS.100%29.aspx

Stefan
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