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

问题描述:

是否可以在一个语句中使用字符串键/值对创建并初始化一个System.Collections.Generic.Dictionary对象?是否可以使用字符串键/值对初始化新System.Collections.Generic.Dictionary?

我沿着构造为一个字符串数组的行思维..

例如

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

如果这原来是一个syntactic sugar之类的话,我宁愿我可以.NET 2.0中使用应答(Visual Studio 2005中)和Visual Basic - 尽管我很好奇如果有可能,在所有所以不要让这把你赶走; O)

我不我认为有办法做t他在VB.NET 2中开箱即可,但是您可以扩展通用字典以使其按您希望的方式工作。

下控制台应用程序进行了说明:

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 

试试这个语法:

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

但是,可能需要C#3(.NET 3.5)

+0

它要求C#3,但它并不需要.NET 3.5。 – 2008-11-25 20:25:39

像这样:

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

这是我正在寻找的答案。 :) – kamranicus 2010-07-23 16:19:10

+8

可用于VB.NET 10 – 2010-10-12 14:36:44

我知道这是一个老的文章,但这个问题频繁出现。如果

下面是声明&初始化的字典在一个语句的方式:

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