首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

请问关于集合的枚举和移除有关问题

2012-02-05 
请教关于集合的枚举和移除问题如果需要遍历一个集合类型,并且在符合条件的时候移除相应的元素,请问应该怎

请教关于集合的枚举和移除问题
如果需要遍历一个集合类型,并且在符合条件的时候移除相应的元素,请问应该怎么处理呢?
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);
}

热点排行