且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在foreach循环中删除列表中的项目C#

更新时间:2021-10-25 03:39:23

尝试为需要删除的项目创建另一个临时列表,然后在完成循环后,只需删除临时列表中的项目即可.

Try just creating another temporary list for the items that need to be deleted then when your done looping you can just delete the ones in the temp list.

List<Type> temp = new List<Type>()
foreach(item in mainList)
{
   if (item.Delete)
   {
      temp.Add(item);
   }
}

foreach (var item in temp)
{
   mainList.Remove(item);
}