Is it possible to initialise a New System.Collections.Generic.Dictionary with String key/value pairs?

匆匆过客 提交于 2019-12-04 23:52:30

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

Like this:

Dim myDic As New Dictionary(Of String, String) From {{"1", "One"}, {"2", "Two"}}

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)

Orry

I know this is an old post but this question frequently comes up. If

Here is a way to declare & initialize a dictionary in one statement:

Private __sampleDictionary As New Dictionary(Of Integer, String) From
{{1, "This is a string value"}, {2, "Another value"}}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!