.NET更改内循环时循环的次数

时间:2014-06-11 10:00:45

标签: vb.net

我正在调查如何在循环内部修改循环结束值。这是.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#代码,但是因为它没有产生相同的行为而把它拿出来。

2 个答案:

答案 0 :(得分:6)

如果您在循环浏览时从列表中删除某些内容,则应该从最后开始。 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;

结束语

这将影响循环。 但是,如果你从最后开始,整个问题就会消失。

答案 1 :(得分:2)

我认为使用while loop符合您的要求

VB代码:

'inital value is 31
Dim currentNumberOfRowsInDataTable As Int32 = dataTable.Rows.Count - 1
Dim i As Integer = 0

While i <= 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
        Else  
            i += 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
End While

修改 我删除了C#代码,因为你使用的是VB.NET,看起来你不需要进行C#转换。正如@Damien_The_Unbeliever所说,如果我们删除i处的行,那么下一行将取代已删除的行,因此我前面的代码将导致在{{的当前行时缺少对下一行的检查1}}被删除。为了避免这种情况,请将i的增量放入i块,这样else只会在没有删除行的情况下增加。我更新了上面的代码