如何在 foreach 循环中删除数组的当前元素?
我的程序从数据库中获取数据并通过 HTTP 请求将其发送到新数据库。现在我想将一个 JSON 字符串发布到我的新数据库中。如果成功,我想删除我正在使用的当前数组项。像这样。
foreach(var item in array)
{
bool decide = method.DoSomething();
if(decide == true)
{
//delete current item
}
}
最佳答案
因为您不能从数组中删除项目并更改它的大小,所以这里是使用第二个集合的循环方法
List<itemClass> keepCollection = new List<itemClass>();
foreach(var item in array)
{
bool decide = method.DoSomething();
if(decide == false)
{
keepCollection.Add(item);
}
}
如果您再次需要数组形式,只需调用 ToArray()
var finalResult = keepCollection.ToArray();
关于c# - 删除数组中的当前元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73690198/