user1570048
user1570048

Reputation: 880

VB.NET Datatable.Select expression

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

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

my linq try was

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!

Upvotes: 0

Views: 17569

Answers (1)

Victor Zakharov
Victor Zakharov

Reputation: 26414

DataTable.Select allows you to specify a filter as a 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 DataRow as you originally had. If you were to return only specific columns, you would need another DataTable to contain them.

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.

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

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 .Add rows to a DataTable, because returned enumeration is not of type DataRow. If you need it badly, here is an implementation on MSDN.

Upvotes: 1

Related Questions