Reputation: 555
I have a DataTable dt
and need to store the first n
items of a certain column in an integer array. I know it's easy to do this with a loop like this:
Dim array(n-1) As Integer
For i As Integer = 0 To n-1
array(i) = dt.Rows(i).Item("columName")
Next
Nonetheless, is there a more convenient way to store these items in the array?
Upvotes: 0
Views: 2640
Reputation: 460138
"Without using a loop" is impossible since there is no magic way to retrieve items from a collection without looping it. However, maybe you think that LINQ does not use loops:
Dim columNameValues = From row In dt
Select row.Field(Of Int32)("columName")
Dim array As Int32() = columNameValues.ToArray()
Gets all values from all rows, if you want to get n
values use Enumerable.Take
:
Dim array As Int32() = columNameValues.Take(n).ToArray()
In VB.NET you can even use Take
in a LINQ query:
Dim first10Values = From row In dt
Select row.Field(Of Int32)("columName")
Take 10
For what it's worth, as Barry has mentioned it is technically possible to get n
items from a collection without using a loop, but see yourself:
Dim value1 As Int32 = dt.Rows(0).Field(Of Int32)("columName")
Dim value2 As Int32 = dt.Rows(1).Field(Of Int32)("columName")
Dim value3 As Int32 = dt.Rows(2).Field(Of Int32)("columName")
' ..... '
Dim value10 As Int32 = dt.Rows(9).Field(Of Int32)("columName")
You could add them to a List(Of Int32)
, but that's just for demonstration purposes anyway.
Upvotes: 4