我只想通过LINQ的Take将一定数量的行返回到DataTable中,或者在Rows属性上使用它,但我不确定如何或在何处执行:这是当前代码:
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
会是这样的:
Dim dt As DataTable = GetDataTable("sp", params).AsEnumerable().Take(10)
当我运行上述内容时,我收到错误:
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]'输入'System.Data.DataTable'。
答案 0 :(得分:1)
如果您需要DataTable
:
Dim dt As DataTable = (From row in GetDataTable("sp", params) Take 10).CopyToDataTable()
如果您需要List(Of [Or])
(您需要括号,因为Or
是关键字)
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()
修改:
有没有一种方法我还可以包含一个带有Take的地方,例如,我的表中有3种状态,Open,Semi-Open,Closed,我只想拿10打开,但我想离开仅半开放和封闭。作为一个例子,半开放和封闭将合并5个记录,我将从Open获得10个,所以我将得到总共15行
是的,有办法:
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()