今天在使用foreach循环遍历list集合时,出现Collection was modified; enumeration operation may not execute.这个错误,查了半天才发现是当想要修改list集合时,不能使用foreach,因为foreach是取只读的,在取的时候数据不能变(包括修改,删除,添加等),所以要写for循环。
在for循环里面,删除操作结束,一定要 i-- 操作。不然会漏掉部分元素。
for
(int i = 0; i < result.Count;i++ )
{
DateTime tTGL = Convert.ToDateTime(result[i].TTGL, dtFormat);
if (DateTime.Compare(date_From, tTGL) > 0 || DateTime.Compare(date_To, tTGL) < 0)
{
result.Remove(result[i]);
i--;
}
}