foreach循环遍历list出错

今天在使用foreach循环遍历list集合时,出现Collection was modified; enumeration operation may not execute.这个错误,查了半天才发现是当想要修改list集合时,不能使用foreach,由于foreach是取只读的,在取的时候数据不能变(包括修改,删除,添加等),因此要写for循环。spa

 在for循环里面,删除操做结束,必定要 i-- 操做。否则会漏掉部分元素。orm

 

forio

 

 

(int i = 0; i < result.Count;i++ )for循环

                {class

                   

 

DateTime tTGL = Convert.ToDateTime(result[i].TTGL, dtFormat);date

                   

 

if (DateTime.Compare(date_From, tTGL) > 0 || DateTime.Compare(date_To, tTGL) < 0)foreach

                    {循环

                        result.Remove(result[i]);遍历

        i--;im

                    }

                }

相关文章
相关标签/搜索