C# NameValueCollection: Should we check if key exists before we remove those?

1.5k Views Asked by At

We want to remove few keys from a NameValueCollection but we are not sure if they actually exist in it or not.

If i try to remove key1 which isn't in NameValueCollection, there's no exception/side-effect:

nameValues.Remove("key1");

But what is ideal way to do this, should we check if key exist before removing it?

1

There are 1 best solutions below

1
On BEST ANSWER

The answer is no. You don't need to check the key before trying to remove it. No exception is thrown if the key doesn't exist.

I believe you should not do that because of it cause you O(n) * 2 operations.

  • O(n) for checking
  • O(n) for trying to delete