Title says it mostly. I want to add a simple extension method to the base Dictionary class in C#. At first I was going to name it Pop(TKey key), kind of like the Stack method, but it accepts a key to use for lookup.
Then I was going to do Take(TKey key), but it coincides with the LINQ method of the same name…and although C# 3.0 lets you do it, I don’t like it.
So, what do you think, just stick with Pop or is there a better term for ‘find and remove an element’?
(I feel kind of embarrassed to ask this question, it seems like such a trivial matter… but I like to use standards and I don’t have wide experience with many languages/environments.)
EDIT: Sorry, should have explained more…. In this instance I can’t use the term Remove since it’s already defined by the class that I’m extending with a new method.
EDIT 2: Okay, here’s what I have so far, inspired by the wisdom of the crowd as it were:
public static TValue Extract<TKey, TValue> ( this Dictionary<TKey, TValue> dict, TKey key ) { TValue value = dict[key]; dict.Remove(key); return value; } public static bool TryExtract<TKey, TValue> ( this Dictionary<TKey, TValue> dict, TKey key, out TValue value ) { if( !dict.TryGetValue(key, out value) ) { return false; } dict.Remove(key); return true; }
I reckon Extract, like when archaeologists Find a mummy in the ground, Remove it and then Return it to a museum 🙂