[英]C# Remove item from nested dictionary
我有一個簡單的問題,我的想法是空白:我有一個字典,看起來像這樣:
Dictionary<string, Dictionary<string, string>> dict;
據我所知,dict.Remove()會通過鍵刪除任何條目,但是我只需要從最里面的字典中刪除一個項目。 我將如何處理?
好吧,大概您有兩個鍵:一個用於外部詞典,另一個用於嵌套鍵。
因此,假設您知道該條目存在,則可以使用
dict[outerKey].Remove(innerKey);
如果您不知道該條目是否存在,則需要以下內容:
Dictionary<string, string> innerDict;
if (dict.TryGetValue(outerKey, out innerDict))
{
// It doesn't matter whether or not innerKey exists beforehand
innerDict.Remove(innerKey);
}
如果只有內鍵,則可以執行以下操作:
string removeKey = "42";
Dictionary<String, String> removeDict = dict.Select(d=> d.Value).FirstOrDefault(d => d.ContainsKey(removeKey));
if(removeDict !=null)
removeDict.Remove(removeKey);
在此實現中,如果有多個具有相同innerKey的寄存器,則只會刪除第一個匹配項
嘗試
dict["key"].Remove("childkey");
請注意,鍵是字符串值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.