从字典中获取键值并删除该键

本文关键字:删除 键值 字典 获取 | 更新日期: 2023-09-27 17:51:02

我有一些代码

muVar = 5782347242-8923423423-3423423432;

,然后添加到dict中。{交货1:57,2:82年,3:34岁,4:72年,5:42岁,6 : -, ....}我尝试得到这个var

的路径
foreach (KeyValuePair<int, string> kvp in myDict)
{
    if (kvp.Value == "-") { myDict.Remove(kvp.Key);  break; }
    foreach (KeyValuePair<string, string> kvp2 in dict2)
    {
        if (kvp.Value == kvp2.Value) var1 += kvp2.Key;
    }
    myDict.Remove(kvp.Key);
}
foreach (KeyValuePair<int, string> kvp in myDict)
{
    if (kvp.Value == "-") { mytDict.Remove(kvp.Key); break; }
    foreach (KeyValuePair<string, string> kvp2 in dict2)
    {
        if (kvp.Value == kvp2.Value) var2 += kvp2.Key;
    }
    myDict.Remove(kvp.Key);
}

但是我有一个异常"Collection was modified;

从字典中获取键值并删除该键

你的foreach循环正在使用这个集合所以你不能在循环之间修改

尝试使用ToList()

    foreach (KeyValuePair<int, string> kvp in myDict.ToList())
{
    if (kvp.Value == "-") { myDict.Remove(kvp.Key);  break; }
    foreach (KeyValuePair<string, string> kvp2 in dict2)
    {
        if (kvp.Value == kvp2.Value) var1 += kvp2.Key;
    }
    myDict.Remove(kvp.Key);
}
foreach (KeyValuePair<int, string> kvp in myDict.ToList())
{
    if (kvp.Value == "-") { mytDict.Remove(kvp.Key); break; }
    foreach (KeyValuePair<string, string> kvp2 in dict2)
    {
        if (kvp.Value == kvp2.Value) var2 += kvp2.Key;
    }
    myDict.Remove(kvp.Key);
}

你必须收集你想从字典中删除的所有项:

Dictionary<int, string> removeDict = new Dictionary<int, string>();
foreach (KeyValuePair<int, string> kvp in myDict)
{
    if (kvp.Value == "-") { myDict.Remove(kvp.Key);  break; }
    foreach (KeyValuePair<string, string> kvp2 in dict2)
    {
        if (kvp.Value == kvp2.Value) var1 += kvp2.Key;
    }
    removeDict.Add(kvp.Key);
    //myDict.Remove(kvp.Key);
}
foreach (KeyValuePair<int, string> kvp in myDict)
{
    if (kvp.Value == "-") { mytDict.Remove(kvp.Key); break; }
    foreach (KeyValuePair<string, string> kvp2 in dict2)
    {
        if (kvp.Value == kvp2.Value) var2 += kvp2.Key;
    }
    removeDict.Add(kvp.Key);
    //myDict.Remove(kvp.Key);
}

然后从字典中删除它们:

foreach (KeyValuePair<int, string> kvp in removeDict)
{
    myDict.Remove(kvp );
}

您不允许在foreach循环中删除或添加某些内容到Collection。但是你从mydict myDict.Remove(kvp.Key);中删除了一些东西。

您可以将要删除的键保存在列表中,然后再删除它们。