views:

1887

answers:

4

Is it possible to create and initialise a System.Collections.Generic.Dictionary object with String key/value pairs in one statement?

I'm thinking along the lines of the constructor for an array of Strings..

e.g.

Private mStringArray As String() = {"String1", "String2", "etc"}

In case this is turns out to be a syntactic sugar kind of thing, I'd prefer an answer that I can use in .Net 2.0 (Visual Studio 2005), and Visual Basic - though I'm curious if it's possible at all so don't let that put you off ;o)

+2  A: 

Well, I think in C# 3.0 this works:

private Dictionary mDictionary = new Dictionary { {"key", "value"} };

but it looks like you want VB, not sure if there is something similar.

Hope that helps!

Zachary Yates
+3  A: 

Try this syntax:

Dictionary<string, double> dict = new Dictionary<string, double>()
{
  { "pi", 3.14},
  { "e", 2.71 }
 };

But that may require C# 3 (.NET 3.5)

Kasprzol
It does require C# 3, but it doesn't require .NET 3.5.
Jon Skeet
+3  A: 

I don't think there is a way to do this out of the box in VB.NET 2, however you can extend the generic dictionary to make it work the way you want it to.

The console app below illustrates this:

Imports System.Collections.Generic

Module Module1

    Sub Main()

        Dim items As New FancyDictionary(Of Integer, String)(New Object(,) {{1, "First Item"}, {2, "Second Item"}, {3, "Last Item"}})
        Dim enumerator As FancyDictionary(Of Integer, String).Enumerator = items.GetEnumerator

        While enumerator.MoveNext
            Console.WriteLine(String.Format("{0} : {1}", enumerator.Current.Key, enumerator.Current.Value))
        End While

        Console.Read()

    End Sub

    Public Class FancyDictionary(Of TKey, TValue)
        Inherits Dictionary(Of TKey, TValue)

        Public Sub New(ByVal InitialValues(,) As Object)

            For i As Integer = 0 To InitialValues.GetLength(0) - 1

                Me.Add(InitialValues(i, 0), InitialValues(i, 1))

            Next

        End Sub

    End Class

End Module
KevB
+4  A: 

Like this:

Dim myDic As New Dictionary(Of String, String) From {{"1", "One"}, {"2", "Two"}}
jgauffin
This is the answer I was looking for. :)
subkamran
Available as of VB.NET 10
Mauricio Scheffer