TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# NameValueCollection Usage

This C# tutorial shows the NameValueCollection type. It provides benchmarks.

NameValueCollection allows many values for one key.

It is found in System.Collections.Specialized. It does not provide excellent performance. Other collections are likely to be faster for your program.

Example. First, we create a new NameValueCollection. We then adds four string key-value pairs to it. The keys can occur more than once, but map to the same array of values. You can have one key pointing to two values.

String Literal

C# program that uses NameValueCollection

using System;
using System.Collections.Specialized;

class Program
{
    static NameValueCollection GetCollection()
    {
	NameValueCollection collection = new NameValueCollection();
	collection.Add("Sam", "Dot Net Perls");
	collection.Add("Bill", "Microsoft");
	collection.Add("Bill", "White House");
	collection.Add("Sam", "IBM");
	return collection;
    }

    static void Main()
    {
	NameValueCollection collection = GetCollection();
	foreach (string key in collection.AllKeys) // <-- No duplicates returned.
	{
	    Console.WriteLine(key);
	}
    }
}

Output

Sam
Bill

In this example, GetCollection returns a new NameValueCollection. The collection maps two names (Sam, Bill) to four values. In other words, two keys are mapped to two string arrays. The NameValueCollection always acts on strings.

String Array

Also: The NameValueCollection defines an AllKeys property. We use it in a foreach-loop to see all the keys in the collection.

PropertyForeach

Get value. Here we get a value in the collection using a string key. This is how you can use AppSettings in ASP.NET, or the QueryString collection. The collection returns null as a value if the key is not found.

And: If more than one value is found, the string returned contains the values joined by commas.

C# program that uses NameValueCollection indexer

using System;
using System.Collections.Specialized;

class Program
{
    static void Main()
    {
	NameValueCollection collection = GetCollection();
	Console.WriteLine(collection["Sam"]); // <-- Same as GetValues
	Console.WriteLine(collection["X"] == null); // <-- Not found
    }
}

Output

Dot Net Perls,IBM
True

Get methods. Here we see that the NameValueCollection also allows you to test whether there are keys, with HasKeys. It also lets you use GetKey with an index to get the key at that index. You can use Get to get the value at that index.

Note: My research has shown that the fastest way of accessing values in small NameValueCollections is with these methods.

C# program that uses Get

using System;
using System.Collections.Specialized;

class Program
{
    static void Main()
    {
	NameValueCollection collection = GetCollection(); // <-- See first example

	// Write whether the collection has keys.
	Console.WriteLine(collection.HasKeys());

	// Write the first key.
	Console.WriteLine(collection.GetKey(0));

	// Get the first value.
	string value = collection.Get(0);
	Console.WriteLine(value);
    }
}

Output

True
Sam
Dot Net Perls,IBM

Remove value. You can also remove a key-value pair using the Remove method on NameValueCollection. This method requires that you pass it a string key for the pair. I found that you can remove a nonexistent value without throwing an exception.

Also: If you remove a key of NameValueCollection, all its values are also removed.

Count pairs. You can count all the key-value pairs in the NameValueCollection. With the Count property, all the duplicate keys are considered separated. Each pair, even if it has the same key as another, is counted separately.

Note: To test this, add multiple identical keys, and then check the Count. Duplicates add to the result of Count.

ASP.NET. The NameValueCollection is prevalent in ASP.NET, and it is used in appSettings, QueryString, and Headers collections. First, it is used in appSettings, which allows you to retrieve settings from your Web.config file.

appSettings

QueryString usage. The NameValueCollection is also used in the query string collection in ASP.NET. You can access the query values very quickly simply by specifying the string key. This may not be optimal.

QueryString

Benchmark. Here we see sample code that was benchmarked. To reproduce the benchmark, you will need to paste the code blocks into a test harness and compile in Release mode outside of the debugger.

NameValueCollection tested

var collection = new NameValueCollection();
collection.Add("Sam", "Dot Net Perls");
collection.Add("Bill", "Microsoft");
collection.Add("Steve", "Apple");
collection.Add("Rupert", "News Corporation");

Dictionary tested

var dictionary = new Dictionary<string, string>();
dictionary.Add("Sam", "Dot Net Perls");
dictionary.Add("Bill", "Microsoft");
dictionary.Add("Steve", "Apple");
dictionary.Add("Rupert", "News Corporation");

NameValueCollection statement tested

string value = collection["Steve"];

Dictionary statement tested

string value = dictionary["Steve"];

Results: 10 million iterations

NameValueCollection lookup: 2768 ms
Dictionary lookup:           407 ms [faster]

The NameValueCollection's lookup speed on even a small collection was poor. Its performance is likely much worse in many situations. Therefore, the collection must be tested before being used in performance-critical code.

Summary. We used NameValueCollection in the C# language. The collection is located in the System.Collections.Specialized namespace. It allows you to associate one string key with multiple string values.

Note: The collection concatenates values with commas, and returns string arrays.

Warning: It has serious performance drawbacks, and should be avoided unless it is tested thoroughly in your application.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf