Is there any implementation for deleting by key and getting the value at the same time?

I am doing a performance-critical program (few academic materials), and I try to optimize it wherever possible (not as "this" bottleneck was proven).

I have a custom dictionary structure (wrapper around the .NET Dictionary<,> ), and I would constantly delete elements at one stage (by Key value). I need Value deleted items. Now I have to do:

 T t; if !TryGet(key, out t) return false; Remove(key); 

These are two searches. I would like it:

 public bool Remove(S key, out T value) { // implementation } 

I know that there is nothing in the framework, but is there an implementation somewhere? If so, I would change my maintenance dictionary with this.

Edit: I know that both TryGetValue and Remove are O (1). Just knowing if there is any collection structure that will give the same effect in only one search. As I said, I try to optimize as much as possible. Just knowing.

+3
source share
3 answers

The University of Copenhagen Collection Collection Library has a Dictionary.Remove() method that seems to do what you want:

bool Delete (K k, out V v)

Returns true if the dictionary contains an entry whose key is k and if it deletes this entry and assigns the associated value v; otherwise returns false and assigns a default value for T in v.

I did not use this library myself, but I saw it several times here in Stack Overflow. It can be freely used on a commercial basis, subject to this MIT-style license .

+5
source

Dictionary<TKey, TValue>.TryGetValue and Dictionary<TKey, TValue>.Remove are O (1) operations, so I don’t think you should worry about performance here.

+9
source

ConcurrentDictionary has a TryRemove method that does this. It works the same as TryGet , but also removes the item.

+1
source

All Articles