我正在调查如何在循环内部修改循环结束值.这是.NET2代码(我正在使用VB).我明白这不太理想,但可以做到吗?
'inital value is 31 Dim currentNumberOfRowsInDataTable As Int32 = dataTable.Rows.Count - 1 For i As Integer = 0 To currentNumberOfRowsInDataTable Try If (dataTable.Rows(i)("DataItemSection") = "Platforms") Then Dim newRow As DataRow = rearrangedDataTable.NewRow() 'do stuff dataTable.Rows.RemoveAt(i) 'decrement to 30, however this has no influence on the loop currentNumberOfRowsInDataTable -= 1 End If Catch 'problem is that loop always goes to 31, whereas I want it to go to 30 'so need to swallow the exception here End Try Next
编辑 - 这里有C#代码,但是因为它没有产生相同的行为而取出它.
如果你在循环中从List中删除某些东西,你应该从最后开始.C#:
for (int i = currentNumberOfRowsInDataTable - 1; i >= 0; --i) { //the rest here }
引用:
//decrement to 30, however this has no influence on the loop currentNumberOfRowsInDataTable -= 1;
结束报价
这将影响循环.但是,如果你从最后开始,整个问题就会消失.