NameValueCollection
With this VB.NET collection, we can store many values for a single key. All keys and values must be strings.
We can access values associated with a key, and loop over all keys with AllKeys
. And we can get keys and values by index by passing an Integer argument.
We import the System.Collections
Specialized namespace to allow the NameValueCollection
to be more easily accessed in this VB.NET program.
NameValueCollection
. For the strings "cat" and "dog", we add 2 values each.NameValueCollection
, we access the AllKeys
property in a For-Each
loop.NameValueCollection
directly.NameValueCollection
, consider using the HasKeys
property.GetKey
and an index argument—the internal storage of the NameValueCollection
can be accessed by index.GetKey
, the Get()
Function is a way to access values by their index.Imports System.Collections.Specialized Module Module1 Sub Main() ' Part 1: create a NameValueCollection. Dim collection = New NameValueCollection() collection.Add("cat", "orange") collection.Add("dog", "brown") collection.Add("dog", "white") collection.Add("cat", "black") ' Part 2: use for-each over AllKeys. For Each key In collection.AllKeys Console.WriteLine(key) Next ' Part 3: access values using keys. Console.WriteLine(collection("cat")) Console.WriteLine(IsNothing(collection("x"))) ' Part 4: call HasKeys. Console.WriteLine(collection.HasKeys()) ' Part 5: call GetKey at index 0. Console.WriteLine(collection.GetKey(0)) ' Part 6: call Get at index 0. Dim value = collection.Get(0) Console.WriteLine(value) End Sub End Modulecat dog orange,black True True cat orange,black
NameValueCollection
is a built-in way to associate multiple values with a single key. Its performance is not ideal, and in most VB.NET programs we are better served by Dictionary
or List
.