如果需要遍历一个集合类型,并且在符合条件的时候移除相应的元素,请问应该怎么处理呢?
foreach (string key in dictionary.Keys)
{
if (...) dictionary.Remove(key);
}
在以上foreach遍历中,如果移除了集合中的元素,就会引发异常。
foreach (string key in dictionary.Keys)
{
if (...) dictionary.Remove(key);
}
在以上foreach遍历中,如果移除了集合中的元素,就会引发异常。
for (int i = 0; i < dictionary.Keys.Count; i++)
{
if (...)
dictionary.Remove(dictionary.Keys[i]);
}
for (int i = 0; i < dictionary.Keys.Count; i++)
{
if (...)
dictionary.Remove(dictionary.Keys[i]);
}
这里Keys[i]编译失败...
string[] keys = new string[dictionary.Keys.Count];dictionary.Keys.CopyTo(keys, 0);foreach (string key in keys)
{
dictionary.Remove(key);
}
例如:
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("1", 1);
dictionary.Add("2", 2);
string[] keys = new string[dictionary.Keys.Count];
dictionary.Keys.CopyTo(keys, 0);
foreach (string key in keys)
{
if( key=="2")
dictionary.Remove(key);
}