The Muffin Man
The Muffin Man

Reputation: 20004

KeyValuePair vs. NameValueCollection

There are other questions such as KeyValuePair vs IDictionary, but I feel this one differs slightly.

NameValueCollection takes a string key and string value.

KeyValuePair is like a dictionary, you tell it what type the key and value is.

I don't understand why NameValueCollection exists. Initializing a KeyValuePair with string types seems sufficient. I also noticed that NameValueCollection has some more methods available to it, but again why not merge both classes into one?

Upvotes: 13

Views: 19484

Answers (3)

user166390
user166390

Reputation:

A KeyValuePair not like a dictionary. It is simply a Tuple containing the Key and the Value.

NameValueCollection is wrapper over what amounts to a IList<KeyValuePair<string,IList<string>>> (note that NameValueCollection predates generics) - operations like Get(string) are O(n) and items can be fetched by index and each Key maps to one or more Values (this differs from a Dictionary<string,string>).

A reason for this is explained in the NameValueCollection documentation:

This class can be used for headers, query strings and form data.

The newer "replacement" data-structure with some similar behavior for NameValueCollection is Lookup<string,string>. (However, it doesn't directly support the same operations as is immutable as spender notes.)

Happy coding.

Upvotes: 19

bevacqua
bevacqua

Reputation: 48496

KeyValuePair is the component you use to iterate a Dictionary

var dictionary = new Dictionary<int,long>

foreach(var kvp in dictionary)
{
    // kvp is KeyValuePair<int,long>. kvp.Key is the int key and kvp.Value is the long value for the key
}

NameValueCollection is indexable.

Upvotes: 0

shf301
shf301

Reputation: 31394

NameValueCollection existing in .NET 1.0 and 1.1, KeyValuePair is a generic type and wasn't added to .NET until 2.0. All the classes in System.Collections.Specialized all predates the addition of generics; it contains certain strongly typed (specialized if you will) for use when that's exactly what you need to users don't have to cast from object to string.

Upvotes: 4

Related Questions