Hashtable htt = new Hashtable();
for (int i = 0; i < 100; i++)
{
htt.Add(i, i);
}
MessageBox.Show(htt.Count.ToString()); foreach (DictionaryEntry de in htt)
{
if ((int)de.Key % 2 == 0)
{
htt.Remove(de.Key);
}
}
MessageBox.Show(htt.Count.ToString());提示错误:集合已经修改,枚举操作可能不会执行.
请大家帮我分析一下,谢谢了!
for (int i = 0; i < 100; i++)
{
htt.Add(i, i);
}
MessageBox.Show(htt.Count.ToString()); foreach (DictionaryEntry de in htt)
{
if ((int)de.Key % 2 == 0)
{
htt.Remove(de.Key);
}
}
MessageBox.Show(htt.Count.ToString());提示错误:集合已经修改,枚举操作可能不会执行.
请大家帮我分析一下,谢谢了!
解决方案 »
- winform远程获取服务器端ip
- c# winform中怎么实现表格布局tableLayoutPanel除外
- 关于使用 SOCKET 类的求助!!
- datagridview在绑定到数据源是能否暂不显示数据源的数据?
- DropDownList 自动检索功能的完善?
- [提问]请问以下报错的解决方法
- 关于jmail ,为什么会弹出“the message war undeliverable,all servers failed to receive the message"
- 关于DataSet.Table[0].Row的问题,请大侠执教!
- 急!关于在Web窗体中使用自定义javascript函数的问题
- vs.net中的下拉框
- 关于配置文件的问题
- 服务器遇到内部错误。有关更多信息,请打开服务器的 .config 文件中的 customErrors。
能够在循环体内部添加和删除遍历的集合体, 只能够修改.把下面的foreach改为for循环就可以了, 但根据你的思路, 每 htt.Remove(de.Key); 操作后要进行 i--操作, 如下:
for (int i = 0; i < htt.Count; i++)
{
if ((int)htt[i].Key % 2 == 0)
{
htt.Remove(de.Key);
i--;
}
}
{
htt.Remove(...);
}
foreach (DictionaryEntry de in temp)
{
if ((int)de.Key % 2 == 0)
{
htt.Remove(de.Key);
}
}
temp=htt;
foreach (DictionaryEntry de in temp)
{
if ((int)de.Key % 2 == 0)
{
htt.Remove(de.Key);
}
}
using System.Collections;namespace HashtableTest
{
class Program
{
static void Main(string[] args)
{
// 哈希表默认容量是 7,内部数组初始大小为 11
// 每次扩容性能损失相当大,所以最好直接给定 capacity 值
Hashtable htt = new Hashtable(100); for (int i = 0; i < 100; i++)
htt.Add(i, i);
Console.WriteLine(htt.Count); // 使用一个副本,退出 foreach 就回收了,不会造成大的性能影响
foreach (int key in ((Hashtable)htt.Clone()).Keys)
if (key % 2 == 0)
htt.Remove(key);
Console.WriteLine(htt.Count);
}
}
}