Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

DataTable & Row Number Question

Status
Not open for further replies.

RhythmAddict112

Programmer
Jun 17, 2004
625
US
Hey boys 'n girls -
Real quick Q..

Formally, I was coding my loop through a data table like...
Code:
        Dim s As New List(Of String)(dt.Rows.Count)
        Dim dr As DataRow
        For Each dr In dt.Rows
            s.Add(dr("FirstName").ToString)
        Next
        Return s.ToArray

However...I need to exit my for loop when I hit 5 rows. As a quick fix I'm doing it like this...

Code:
        Dim s As New List(Of String)(dt.Rows.Count)
        For i As Int16 = 0 To dt.Rows.Count - 1
            If i > 4 Then Exit For
            s.Add(dt.Rows(i).Item(0))
        Next

So my question...is the 2nd way much worse/less performant/messier than the first? Is there an easy way for me to get the row number in the first method? Thanks!

 
The only other way I can think of to do what you are looking to do is as follows:

Code:
Dim s As New List(Of String)(dt.Rows.Count)
Dim i As Integer = 0
For Each dr In dt.Rows
  i += 1
  If i > 4 Then Exit For
  s.Add(dr("FirstName").ToString)
Next

However, there's not much difference compared with what you have suggested already. As far as performance impact, you'd probably just want to test both blocks of code and see if one runs consistently faster.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top