0

我只想通过 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__3a1[System.Data.DataRow]' 输入'System.Data.DataTable'。`

4

1 回答 1

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 中包含一个 Where,例如,我的表中有 3 个状态,Open、Semi-Open、Closed,我只想拿 10 表示 Open,但我想离开 Semi-Open并单独关闭。例如,Semi-Open 和 Closed 将合并 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()
于 2012-06-05T20:45:14.407 回答