Reputation: 5911
I have a linq query that gets me the data I need. Then I use For Each loop to process it.
Dim PickCustomer as string = "Some Customer"
Dim CustQuery = From Cust In myCustTable _
Select CustomerID = Cust.CustomerID, _
CustName = Cust.Name, _
Order By CustomerID Ascending
For Each MyCust In CustQuery
Next
How can I dynamically change the query? If PickCustomer = "" then I want all the results. But if PickCustomer has a name (any length > 0) then I want to limit my linq query to only that customer. Like Where (CustName = PickCustomer)
I've been checking out dynamic Linq queries but I can't quite make it work.
Upvotes: 0
Views: 174
Reputation: 1
Yes, I agree that there's no need to use dynamic LINQ for this. You can also try logic even outside of the query, like this:
Dim MyCompany as string = "Consolidated Messenger"
Dim companies =
{"Consolidated Messenger", "Alpine Ski House", "Southridge Video", "City Power & Light",
"Coho Winery", "Wide World Importers", "Graphic Design Institute", "Adventure Works",
"Humongous Insurance", "Woodgrove Bank", "Margie's Travel", "Northwind Traders",
"Blue Yonder Airlines", "Trey Research", "The Phone Company",
"Wingtip Toys", "Lucerne Publishing", "Fourth Coffee"}
If MyCompany.length = 0 then
For Each company As String In companies
Console.WriteLine(company)
Next
Else
Dim CompanyResult =
From company In companies where String.IsNullOrEmpty(company) or company.ToLower() = MyCompany.ToLower() select company
For Each comp as String in CompanyResult
Console.WriteLine(comp)
Next
End If
Upvotes: 0
Reputation: 431
I don't think you need dynamic Linq for this. Just add a where clause that deals with both cases. Something like:
Where String.IsNullOrEmpty(PickCustomer) or (CustName = PickCustomer)
Upvotes: 1
Reputation: 8160
Since LINQ queries are lazy evaluated, you can build then up in stages, so you don't really need anything dynamic in this case, just an If
.
e.g. Something like this (untested):
Dim PickCustomer As String = ""
Dim CustQuery = From Cust In myCustTable
If Not String.IsNullOrWhiteSpace(PickCustomer) Then
CustQuery = From Cust In CustQuery
Where Cust.Name = PickCustomer
End If
CustQuery = From Cust In CustQuery
Select
CustomerID = Cust.CustomerID,
CustName = Cust.Name
Order By CustomerID Ascending
For Each MyCust In CustQuery
Next
Upvotes: 1