(vis 781 commented that this may cause the entire collection to be counted each time - information from his university lecturer. this post details a crude investigation of the accuracy of the lecturer's claim)
Did microsoft really write their collections base such that accessing .Count iterates the entire collection?
i wrote the following code in a project I had open..
Debug.Print(DateTime.Now().ToString("hh:mm:ss.ffffff"))
Debug.Print(TestDataSetInstance.BONDETAIL.Rows.Count.ToString())
Debug.Print(DateTime.Now().ToString("hh:mm:ss.ffffff"))
Debug.Print(TestDataSetInstance.BONDETAIL.Rows(0)(0).ToString())
Debug.Print(DateTime.Now().ToString("hh:mm:ss.ffffff"))
For i As Integer = 0 To 10000000
If i Mod 10000 = 0 Then Debug.Print(DateTime.Now().ToString("ss.ffffff"))
Try
If TestDataSetInstance.BONDETAIL.Rows(i) Is Nothing Then
Exit For
End If
Catch ex As Exception
Exit For
End Try
Next i
Debug.Print(DateTime.Now().ToString("hh:mm:ss.ffffff"))
The table had 100,000 rows, the loop took 220 milliseconds to complete, accessing the Rows.Count and Rows(0)(0) each took 30 milliseconds.
Though crude and not very scientific, I would have expected the Rows.Count to take significantly longer than 30 milliseconds (same amount of time to access the first item in the list) if it was iterating the collection. Given that Rows, as a collection, has absolute control over the incomings and outgoings (Add/Range/Remove/Insert) it is very easy for the collection to maintain a count in the same way we do here.. Indeed all the list type structures we wrote at university had a constantly accurate counter of the length of the list - it comes in incredibly handy for e.g. a Linked List if you know that it contains 100 items, and the user asks for 101, you simply say:
if(userRequested > list.length-1) then "no deal"
rather than crawl to the end of the list, counting each as we go, only to find there is none.
So it appears that vis' university lecturer was possibly operating off old information or (if .net has always been this way) incorrect from the outset. The positive upshot is that todoink can use datatable.Rows.Count without fear of significant performance penalty, and this will reduce the coding necessary to count the rows.