如何动态过滤IEnumerable

时间:2014-03-04 02:50:08

标签: asp.net vb.net entity-framework model-binding

我需要使用LINQ构建一个动态查询来过滤IEnumerable的元素 - 它在SelectMethod控件上用作Repeater - 以显示来自我的实体的正确数据模型。我真的不知道从哪里开始。

vb或c#很好,我更喜欢LINQ的基于方法的语法,与查询表达式语法相反,但无论做什么都可以完成...

HTML

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

我想要完成的不好的例子

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

objectContext.CreateQuery()是我唯一能够提供所需功能的功能(我知道),但我的猜测是有更好的方法。所以,请告诉我更好的方法是什么。

我知道我可以在if语句中返回IEnumerable,但这不是我想要的。

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

2 个答案:

答案 0 :(得分:1)

对于linq中的dynamic where子句,我通常按照Build Where Clause Dynamically in Linq提到的方式进行操作。

文章使用Expression树来实现动态有点复杂的地方,但结果在我看来很优雅,并且用C#编写,希望可以帮助你提出一些有关它的想法。

答案 1 :(得分:1)

未优化,但应该完成工作:

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
相关问题