views:

175

answers:

1

Hi, 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 serveral 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 dymanmic, 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 of Objects)

Yours ideas please.

+1  A: 

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
Thomas Levesque
Thanks for this. The problem is I don't know when I am writing the code that I need "A=10" and "C>40", these are dynamic. I don't even know which fields I need to query against. These are determined by other aspects of the code.
Tim
May be it works when using the index?"where r.Field(Of GetType(queryValue))(index) < queryValue"
Robert
@Robert : yes it does
Thomas Levesque
Great Thanks, But what about varying number of fields. Sometimes A=10, other times A=10 and B=20, even A=10 and B=20 or C=30
Tim
Have a look at the PredicateBuilder class, it should help you achieve what you want. http://www.albahari.com/nutshell/predicatebuilder.aspx
Thomas Levesque