VB.NET Datatable.Select 表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12989010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 15:59:46  来源:igfitidea点击:

VB.NET Datatable.Select expression

vb.netlinqselectdatatable

提问by user1570048

is it possible to use filter expression to select some columns? something like select a,b,c from tablein sql

是否可以使用过滤器表达式来选择某些列?类似于select a,b,c from tablesql

here is what i am trying to do

这是我正在尝试做的

 Dim rows() As DataRow = bookedorders.Select("a,b,c")   'select columns a b c only, i know its wrong
        Dim zzz As DataTable = rows.CopyToDataTable

so is it possible to use the Datatable.Select to select columns and the use a condition like sql WHERE a=1

那么是否可以使用 Datatable.Select 来选择列并使用像 sql 这样的条件 WHERE a=1

my linq try was

我的 linq 尝试是

Dim q = From r In bookedorders.AsEnumerable Select r.Field(Of Integer)("a") And r.Field(Of String)("b") And r.Field(Of String)("c") And r.Field(Of Integer)("d")
        For Each m In q
            zzz.Rows.Add(m)
        Next

which doesnt seem to work, it says that the number of items in array is longer than the datatable!

这似乎不起作用,它说数组中的项目数比数据表长!

回答by Neolisk

DataTable.Selectallows you to specify a filter as a String:

DataTable.Select允许您将过滤器指定为String

bookedorders.Select("a = 1")

You cannot specify columns to be extracted because that would break type structure, as it is expected to return same DataRowas you originally had. If you were to return only specific columns, you would need another DataTableto contain them.

您不能指定要提取的列,因为这会破坏类型结构,因为它预计会返回与DataRow您最初相同的内容。如果您只返回特定的列,则需要另一个DataTable来包含它们。

Assuming this functionality existed, limiting number of returned columns is not practical, because you already have your DataRows filled with data, unlike select a,b,c from table, where you can reduce network bandwidth and speed up query performance by specifying only certain columns to be extracted from a database.

假设存在此功能,限制返回列的数量是不切实际的,因为您的DataRows已经填充了数据,这与 不同select a,b,c from table,您可以通过仅指定要从数据库中提取的某些列来减少网络带宽并加快查询性能。

If you want to use LINQ, you can do it like this:

如果你想使用 LINQ,你可以这样做:

From r In bookedorders Select a=r.Field(Of Integer)("a"), b=r.Field(Of String)("b"), c=r.Field(Of String)("c"), d=r.Field(Of Integer)("d")

Note that you cannot use results of this query to directly .Addrows to a DataTable, because returned enumeration is not of type DataRow. If you need it badly, here is an implementation on MSDN.

请注意,您不能使用此查询的结果直接将.Add行转换为 a DataTable,因为返回的枚举类型不是DataRow。如果您非常需要它,这里是MSDN 上的一个实现