代码之家  ›  专栏  ›  技术社区  ›  jitbit

是否可以使用字符串键/值对初始化新System.Collections.Generic.Dictionary?

  •  22
  • jitbit  · 技术社区  · 16 年前

    是否可以创建并初始化 System.Collections.Generic.Dictionary

    我在考虑字符串数组的构造函数。。

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

    如果这是一个 syntactic sugar

    4 回复  |  直到 14 年前
        1
  •  78
  •   jgauffin    14 年前

    这样地:

    Dim myDic As New Dictionary(Of String, String) From {{"1", "One"}, {"2", "Two"}}
    
        2
  •  7
  •   KevB    16 年前

    下面的控制台应用程序说明了这一点:

    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
    
        3
  •  5
  •   Kasprzol    16 年前

    请尝试以下语法:

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

        4
  •  0
  •   Siddharth Rout    12 年前

    以下是一种申报&在一条语句中初始化字典:

    Private __sampleDictionary As New Dictionary(Of Integer, String) From
    {{1, "This is a string value"}, {2, "Another value"}}