Is there a quick and simple way to check if a key exists in a NameValueCollection without looping through it?
Looking for something like Dictionary.ContainsKey() or similar.
There are many ways to solve this of course. Just wondering if someone can help scratch my brain itch.
Yes, you can use Linq to check the
AllKeys
property:However a
Dictionary<string, string[]>
would be far more suited to this purpose, perhaps created via an extension method:You could use the
Get
method and check fornull
as the method will returnnull
if the NameValueCollection does not contain the specified key.See MSDN.
As you can see in the reference sources, NameValueCollection inherits from NameObjectCollectionBase.
So you take the base-type, get the private hashtable via reflection, and check if it contains a specific key.
For it to work in Mono as well, you need to see what the name of the hashtable is in mono, which is something you can see here (m_ItemsContainer), and get the mono-field, if the initial FieldInfo is null (mono-runtime).
Like this
for ultra-pure non-reflective .NET 2.0 code, you can loop over the keys, instead of using the hash-table, but that is slow.
From MSDN:
So you can just:
collection[key]
callsbase.Get()
thenbase.FindEntry()
which internally usesHashtable
with performance O(1).This could also be a solution without having to introduce a new method:
Be aware that key may not be unique and that the comparison is usually case sensitive. If you want to just get the value of the first matching key and not bothered about case then use this: