Reputation: 46651
I only want to return a certain number of rows into the DataTable via LINQ's Take or use it on the Rows property, but I am not sure how or where to do it: Here is the current code:
Dim dt As DataTable = GetDataTable("sp", params)
For Each dr As DataRow In dt.Rows
Dim o As New OR()
o.P = p
o.Id = dr ("A")
o.R = dr ("B")
Next
Would it be something like:
Dim dt As DataTable = GetDataTable("sp", params).AsEnumerable().Take(10)
When I run the above, I get the error:
The 'TakeIterator' start tag on line 4 position 60 does not match the end tag of 'Error'. Line 4, position 137.
Unable to cast object of type '<TakeIterator>d__3a
1[System.Data.DataRow]' to type 'System.Data.DataTable'.`
Upvotes: 0
Views: 702
Reputation: 460288
If you need a DataTable
:
Dim dt As DataTable = (From row in GetDataTable("sp", params) Take 10).CopyToDataTable()
If you need a List(Of [Or])
(you need the brackets since Or
is a keyword)
Dim list As List(Of [Or]) = (From row In GetDataTable("sp", params)
Select New [Or]() {
o.Id = row.Field(Of Int32)("Id"),
o.R = row.Field(Of String)("R")
}).Take(10).ToList()
Edit:
is there a way I can also include a Where with the Take, for example, I have 3 statuses in my table, Open, Semi-Open, Closed, I only want to Take 10 for Open, but I want to leave Semi-Open and Closed alone. As an example Semi-Open and Closed will have 5 records combined and I will take 10 from Open, so I would get a total of 15 rows
Yes, there's a way:
Dim dt = GetDataTable("sp", params)
Dim open10 = From row In dt
Where row.Field(Of String)("Status") = "Open"
Take 10
Dim rest = From row In dt
Where row.Field(Of String)("Status") <> "Open"
Dim tblResult = open10.Concat(rest).CopyToDataTable()
Upvotes: 1