遍历list时删除元素的正确做法

我们往往会遇到需要删除list中满足条件的元素。举例:

List<string> list_str =new List<string>()
{
    "A","B","B","C","D"
}

不能用foreach,因为在迭代的过程中修改元素会使程序崩溃,

也不能直接for循环,因为循环过程中会跳过第二个“B”,导致没删干净

想要删除所有的B,最好用for循环倒序遍历的办法:


for(int i=list_str.Count-1;i>=0;i--)
{
   if(list_str[i]=="B")
   {
     list_str.remove(i);
   }
}



posted @ 2017-12-08 15:05  birdhumen鸟人  阅读(251)  评论(0编辑  收藏  举报