1

I've got a simple question that my mind is drawing a blank to: I have a Dictionary that looks something like this:

Dictionary<string, Dictionary<string, string>> dict;

As far as I know, dict.Remove() would remove any entry by key, but I need to only remove an item from the innermost dictionary. How would I go about that?

2
  • Get the inner dictionary and call Remove() on that. I.e., get the value specified by the key in the parent dictionary. Commented Apr 25, 2015 at 19:49
  • Nested dictionary is a smell. Use appropriate data structure. It could be Dictionary of some class which in turn has a dictionary. Not nested dictionary. Commented Apr 25, 2015 at 19:50

3 Answers 3

3

Well presumably you've got two keys: one for the outer dictionary and one for the nested one.

So assuming you know that the entry is present, you can use

dict[outerKey].Remove(innerKey);

If you don't know whether the entry exists, you want something like:

Dictionary<string, string> innerDict;
if (dict.TryGetValue(outerKey, out innerDict))
{
    // It doesn't matter whether or not innerKey exists beforehand
    innerDict.Remove(innerKey);
}
Sign up to request clarification or add additional context in comments.

Comments

2

If you just have the inner key, you can do something like this:

string removeKey = "42";

Dictionary<String, String> removeDict = dict.Select(d=> d.Value).FirstOrDefault(d => d.ContainsKey(removeKey));

if(removeDict !=null)  
    removeDict.Remove(removeKey);

In this implementation if there is more then one register with the same innerKey just the first occurrence will be removed

Comments

1

Try

dict["key"].Remove("childkey");

Notice the keys are string values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.