Question LINQ expression with variable number of expressions

breakoutfoo

New member
Joined
Dec 17, 2010
Messages
2
Programming Experience
1-3
Hi,

I am creating a form that searches for items based upon search criteria entered into multiple free text fields. None of the fields are to be mandatory and as such I need to be able to write my LINQ in such a way that the conditions to be used can change.

I have around 10 possible fields so there are too many combinations to create a seperate LINQ for each possible combination. I have no idea how to tackle this. Does anybody have any suggestions of the sort of methods I should be looking to use?

Thanks

Andy

Andy
 
One of the cool features of LINQ is the ability to use function syntax to dynamically compose a query that will only be evaluated when the data is actual data is used, e.g.
VB.NET:
Dim products = myDataContext.Products

If Me.nameTextBox.TextLength > 0 Then
    products = products.Where(Function(p) p.Name = Me.nameTextBox.Text)
End If

If Me.priceTextBox.TextLength > 0 Then
    products = products.Where(Function(p) p.Price = CDec(Me.priceTextBox.Text))
End If
When you actually use the data, all those Where clauses get combined into one. You can do the same with other clauses to, e.g. OrderBy or OrdeByDescending.
 
Back
Top