【C#】遍历List列表的同时,移除访问到的元素

需求:遍历List列表,当访问的元素符合某一条件时,将该元素移除出列表。

注意点:使用foreach循环遍历无法做到边读边修改,所以要使用for循环。

例子:

// 倒序遍历。
for (int i = list.Count - 1; i >= 0 ; i--)
{
    if (list[i].name != null)
    {
        // list.Remove(list[i]);
        list.Remove(i);
    }
}

重要参考:

http://stackoverflow.com/questions/1582285/how-to-remove-elements-from-a-generic-list-while-iterating-over-it

原文地址:https://www.cnblogs.com/guxin/p/csharp-how-to-remove-elements-from-a-generic-list-while-iterating-over-it.html