Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the properties Keys and AllKeys on a NameValueCollection?

System.Collections.Specialized.NameObjectCollectionBase has two similar properties:

  string[] AllKeys   NameObjectCollectionBase.KeyCollection Keys 

Do they provide different sets of data? When would I want to use one over the other?

like image 501
MojoFilter Avatar asked Apr 29 '09 17:04

MojoFilter


People also ask

Is NameValueCollection case sensitive?

The default comparer is a CaseInsensitiveComparer that uses the conventions of the invariant culture; that is, key comparisons are case-insensitive by default. To perform case-sensitive key comparisons, call the NameValueCollection.


2 Answers

AllKeys is an O(n) operation, while Keys is O(1). This is because AllKeys copies the keys into a new array, while Keys just returns a reference to NameValueCollection's private key collection. So beyond the difference in performance, the collection returned by Keys will change with the base collection as it's just a reference to the original, while AllKeys will be insulated from the changes because it's a copy.

This little test program shows the difference in behavior:

using System; using System.Collections.Specialized;  static class Program {     static void Main()     {         var collection = new NameValueCollection();          var keys = collection.Keys;         var allKeys = collection.AllKeys;          collection.Add("Name", "Value");          Console.WriteLine("Keys: " + keys.Count);         Console.WriteLine("AllKeys: " + allKeys.Length);         Console.ReadLine();     } } 

The output is:

Keys: 1 AllKeys: 0 
like image 84
Neil Williams Avatar answered Sep 25 '22 00:09

Neil Williams


According to MSDN's documentation, when using AllKeys, it's O(n) to retrieve all the values, whereas when using Keys it's O(1).

Keys

Retrieving the value of this property is an O(1) operation

AllKeys

This method is an O(n) operation, where n is Count.

So basically, it seems that Keys has better performance.

like image 23
BFree Avatar answered Sep 25 '22 00:09

BFree