سؤال

I need to build a dynamic query using LINQ to filter elements of an IEnumerable -which is used as the SelectMethod on a Repeater control- to display the correct data from my entity model. I am really not sure where to start.

vb or c# is fine, and I prefer the method-based syntax of LINQ opposed to query-expression syntax, but whatever gets the job done...

HTML

<asp:Repeater ID="pList" runat="server" ItemType="rsDataAccess.Product" SelectMethod="GetProducts">
  <ItemTemplate>
     ...
  </ItemTemplate>
</asp:Repeater>

Bad example of what I want to accomplish

Public Function GetProducts() As IEnumerable(Of Product)

  Dim products As Product =
  repo.Product.Where(Function(r) r.Status = "Open")

  Dim query As String = ""

  If option1 = True Then
    query += "Where(function(r) r.Price > 100)"
  End If

  If option2 = True Then
    query += "Where(function(r) r.Zip = 63039 "
  End If

  products += query

  Return products
End Function

The objectContext.CreateQuery() is the only function (that I know of) that's even remotely close to providing the functionality that I need, but my guess is that there is a better approach. So please, tell me what that better approach is.

I know that I could just return the IEnumerable inside of the if statements, but that is not what I am looking for.

If option1 = True Then
  Return repo.Products.Where(Function(r) r.Price > 100)
End If

If option2 = True Then
  Return repo.Products.Where(Function(r) r.Zip = 63039)
End If
هل كانت مفيدة؟

المحلول

Not optimized, but should do the job:

Public Function GetProducts() As IEnumerable(Of Product)

   Dim products As IEnumerable(Of Product) =
     repo.Product.Where(Function(r) r.Status = "Open")

   If option1 Then
       products = products.Concat(repo.Product.Where(function(r) r.Price > 100))
   End If

   If option2 Then
       products = products.Concat(repo.Product.Where(function(r) r.Zip = 63039))
   End If

   Return products.Distinct()
End Function

نصائح أخرى

For dynamic where clause in linq, I normally follow the way mentioned by this Build Where Clause Dynamically in Linq.

The article is using Expression tree to achieve the dynamic where which is a bit complicated, but the result is elegant in my opinion, and it is written in C#, hope can help you come out with some ideas about it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top