日期:2014-05-18  浏览次数:20800 次

请教关于集合的枚举和移除问题
如果需要遍历一个集合类型,并且在符合条件的时候移除相应的元素,请问应该怎么处理呢?
foreach   (string   key   in   dictionary.Keys)
{
        if   (...)   dictionary.Remove(key);
}
在以上foreach遍历中,如果移除了集合中的元素,就会引发异常。

------解决方案--------------------
在用foreach 蝶代的过程中,对集合中的元素是不能更改的,只能读

试试这样:
for (int i = 0; i < dictionary.Keys.Count; i++)
{
if (...)
dictionary.Remove(dictionary.Keys[i]);
}

------解决方案--------------------
for each只能向前只读,不能对正在遍历的集合修改。改用for或while可以修改正在遍历的集合
------解决方案--------------------
如下:
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);
}