我有一些代码
muVar = 5782347242-8923423423-3423423432;
比把它添加到dict。 ex {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);
}
但我有一个例外“收集被修改;枚举操作可能无法执行。”;
答案 0 :(得分:1)
您的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);
}
答案 1 :(得分:0)
您必须收集要从字典中删除的所有项目:
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);
}
然后从dictiponary中删除它们:
foreach (KeyValuePair<int, string> kvp in removeDict)
{
myDict.Remove(kvp );
}
答案 2 :(得分:0)
您不能在foreach
循环中删除或添加某些内容。但你从mydict myDict.Remove(kvp.Key);
删除了一些东西。
您可以在列表中保存要删除的键,然后将其删除。