Home
VB.NET
NameValueCollection Usage
Updated Feb 27, 2024
Dot Net Perls
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.
Property
For
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.
Dictionary
List
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 27, 2024 (new).
Home
Changes
© 2007-2025 Sam Allen