开发者

LINQ or DataTable when number of fields unknown

I have a dynamic query which returns a DataTable. This DataTable will contain a varying number of columns depending on the selection used in the query. I want an efficient way of filtering the records in the DataTable.

For Example

The DataTable contains columns : A, B, C and D

I need to query this data at several points in my program.

At some point I may need records where A=10 and C>40. At another point I may need records where A<10 and D=90 etc. etc. The selects are dynamic, I do not now what Columns or values are needed until the code is executing.

I could simply use a DataTable Filter and build the selection string dynamically. I have no problem with this. However I was wondering if using LINQ would be more applicable. I am completely new to LINQ and would like to use it but don't know its capabilities.

(At present I am using a DataTable but in future this may change to a collection 开发者_如何学Cof Objects)

Yours ideas please.


You can use the Linq to DataSet extension methods (declared in System.Data.DataSetExtensions.dll)

Dim table As New DataTable
...

Dim query1 = From r In table.AsEnumerable()
             where r.Field(Of Int32)("A") = 10
             AndAlso r.Field(Of Int32)("C") > 40

For Each row As DataRow In query1
    ' Do something with the row
Next

...

Dim query2 = From r In table.AsEnumerable()
             where r.Field(Of Int32)("A") < 10
             AndAlso r.Field(Of Int32)("D") = 90

For Each row As DataRow In query2
    ' Do something with the row
Next
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜