对集合遍历并删除的问题
我的代码如下,但是这样 一旦真的删除了对象,那么出错, 请问怎么遍历集合 然后根据条件删除元素?
for (int i = 0; i < AppConfig.MyTcpClient.Count; i++ ) { TcpClient c = AppConfig.MyTcpClient[i]; if (c == null || c.Connected == false) { AppConfig.MyTcpClient.Remove(c); } else { User u = new User(); u.name = c.Client.RemoteEndPoint.ToString(); u.MyTcpClient = c; AppConfig.MainFrom.combobox.InvokeIfNeeded((x) => AppConfig.MainFrom.combobox.Items.Add(x), u); } }
{
TcpClient c = AppConfig.MyTcpClient[i];
if (c == null || c.Connected == false)
{
AppConfig.MyTcpClient.Remove(c);
i--;
continue;//这样
}
else
{
User u = new User();
u.name = c.Client.RemoteEndPoint.ToString();
u.MyTcpClient = c;
AppConfig.MainFrom.combobox.InvokeIfNeeded((x) => AppConfig.MainFrom.combobox.Items.Add(x), u);
}
}
[解决办法]
1.要看你集合的类型
2.删除频繁否(得到回答是频繁)
3.集合多大
4.每次删除的的数量有多大。
链表,并且删除的数目小于留下的数目,14楼的不错!
如果删除的数目很多,直接把不需要删除的拷贝到新链表里去。
还有个问题,用链表的话,每次查询元素,效率比较低,不知道其他地方是保存 socket的ID还是引用?
[解决办法]
TcpClient c = AppConfig.MyTcpClient[i];
这个查询 应该也比较慢
[解决办法]
lz的写法应该加上i--