NameValueCollection UsageCreate a NameValueCollection to store multiple string values for a single string key.
This page was last reviewed on Feb 27, 2024.
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.
Example. We import the System.Collections Specialized namespace to allow the NameValueCollection to be more easily accessed in this VB.NET program.
Part 1 We create a NameValueCollection. For the strings "cat" and "dog", we add 2 values each.
Part 2 To loop over the keys in a NameValueCollection, we access the AllKeys property in a For-Each loop.
Part 3 To get a value for an associated key, we can access the NameValueCollection directly.
Part 4 To test for an empty NameValueCollection, consider using the HasKeys property.
Part 5 We can access keys with GetKey and an index argument—the internal storage of the NameValueCollection can be accessed by index.
Part 6 Similar to 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 Module
cat dog orange,black True True cat orange,black
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 27, 2024 (new).
© 2007-2024 Sam Allen.