开发者

Creating a hashtable with values in VB.NET

开发者 https://www.devze.com 2023-01-19 13:10 出处:网络
Is it possible to create a hashtable \"pre-populated\" with values? That is, something like: dim myHash as new Hashtable() = {\"key1\", \"value1\", \"key2\", \"val开发者_C百科ue2\" }

Is it possible to create a hashtable "pre-populated" with values?

That is, something like:

dim myHash as new Hashtable() = {"key1", "value1", "key2", "val开发者_C百科ue2" }


First of all, Hashtable's are old now. Use a Dictionary(Of TKey, TValue) instead. As for your question, with Visual Studio 2010 you can use the new collection initializer syntax:

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

Since you're on .NET 2.0, you can't use that syntax (you can and should still use a generic Dictionary), and so your best bet is using a method to hide it:

Function CreateDictionary() As Dictionary(Of Integer, String)
    Dim d As New Dictionary(Of Integer, String)
    d.Add(1, "One")
    d.Add(2, "Two")
    Return d
 End Function

Dim myDict As Dictionary(Of Integer, String) = CreateDictionary()


The easiest way to accomplish this is to factor the code out into a function

Function CreateHashtable() As Hashtable
  Dim table = new HashTable()
  table.Add("key1", "value1")
  table.Add("key2", "value2")
  return table
End Function

Dim myHash As Hashtable = CreateHashtable()


    Dim myHash As New Hashtable() From {
        {"key1", "value1"}, {"key2", "value2"}
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号