I’m populating a DataGrid in my .aspx page and have some dropdowns on the page for filtering the data that appears in the grid. I’m trying to use LINQ to filter the data in the DataTable that I bind to on page_load and on the SelecedIndexChanged events of the drop downs.
Here’s my current approach:
Dim filteredData As DataTable = (From d In rawDataTable
Select d).CopyToDataTable
If Me.cbFilter1.SelectedIndex > 0 Then
filteredData = (From f In filteredData
Where f.Field(Of Date)("ADateField").Year = Me.cbFilter1.SelectedValue
Select f).CopyToDataTable
End If
If Me.cbFilter2.SelectedIndex > 0 Then
filteredData = (From f In filteredData
Where f.Field(Of String)("AStringField") = Me.cbFilter2.SelectedValue
Select f).CopyToDataTable
End If
If Me.cbFilter3.SelectedIndex > 0 Then
filteredData = (From f In filteredData
Where f.Field(Of Boolean)("ABooleanField") = (cbFilter3.SelectedValue = "Yes")
Select f).CopyToDataTable
End If
' ...and finally binding my grid to filteredData
Is there a cleaner and more efficient ways to do this? How would you do it?
Thanks!
What you want to be using is the
IQueryableinterface to handle adding multiple where clauses.IQueryableallows you chain Where clauses to your query, while at the same time deferring the execution of the query until you’re ready for the results. The way you’ve outlined executes the queries multiple times. On top of that you’re calling the.CopyToDataTablemethod each time, which may have some additional performance implications.Aside from the fact that you should probably move away from DataSets and DataTables altogether, here’s an example that will help you use them with IQueryable: