简体   繁体   English

C#从嵌套字典中删除项目

[英]C# Remove item from nested dictionary

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. 据我所知,dict.Remove()会通过键删除任何条目,但是我只需要从最里面的字典中删除一个项目。 How would I go about that? 我将如何处理?

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);
}

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 在此实现中,如果有多个具有相同innerKey的寄存器,则只会删除第一个匹配项

Try 尝试

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

Notice the keys are string values. 请注意,键是字符串值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM