您的位置:首页 > 编程语言 > C#

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

2017-04-12 09:42 633 查看
需求:遍历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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C#