For each dtRow in dt.Row reference previous row

jimctr

Well-known member
Joined
Dec 1, 2011
Messages
52
Programming Experience
Beginner
I have the following routine embedded in a For each loop, and I have a counter which keeps track of which row

VB.NET:
Dim CurrentDate = Date.Parse(dtRow.Item("Date-Time"))
                If count > 0 Then   'Cannot generate data on very first datapoint
                    Dim LastDate = Date.Parse(dt.DefaultView.Item(count - 1)("Date-Time"))
                    diff1 = CurrentDate.Subtract(LastDate)
                    If diff1 <= TimeIntervalThreshold Then
                        AmendFlag = False
                    End If
                End If

This piece of code is able to reference the previous row item by using Defaultview and making reference to the counter. Is there any way to achieve the same outcome utilizing dtRow instead of Defaultview?

Thanks
 
Using a For Each loop and then maintaining a counter completely defeats the purpose. If you need a counter than use the type of loop that has a counter inherently, i.e. a For loop, e.g.
Dim rows = myDataTable.Rows

For currentIndex = 1 To rows.Count - 1
    Dim currentRow As DataRow = rows(currentIndex)
    Dim previousRow As DataRow = rows(currentIndex - 1)

    '...
Next
 
Hi:

Yes, I know that using an external counter defeats the purpose. I was in the process of rewriting my code to eliminate the counter altogether and so to my question: I would like to use the For Each looping structure, as with For Each dtRow in dt.Row, but for each iteration save for the first, I need to access the previous row value for a given column as well as the current row value. How is this done, or can it not be done with this particular looping structure?
 
If someone had a hammer hanging off their belt and they told you that they wanted to bang a nail in with a screwdriver, what would you say? Use the right tool for the job. The right tool for this job is the For loop. If you really want to use the language in a way that it was intended for no gain then I guess that's your choice.
 
"You cannot access a previous row with a For Each Loop"
You can declare a variable outside the loop to hold the previous row.
 
A "You cannot access a previous row with a For Each Loop" would have sufficed.
It's not that it's not possible, just like banging in a nail with a screwdriver. It's that it's not the best way to go about it. If you don't have a hammer handy and you need to bang in a nail then you use the screwdriver. If you do have a hammer though, there's no reason not to use it. There's nothing stopping you using a For Loop and that is the most suitable type of loop for this case so that's what you should use.
 
You can get the Table from the current row, and from its Row collection you can get the index of the row using IndexOf method, and access the previous row based on that. Still possible, but even more far-fetched :)
 
Back
Top