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?
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With