那麼,我個人的做法是建立lambda表達式,然後將最終表達式應用到列表中。
我使用了一些擴展方法來Linq.Expression這只是包裝類似如下:
<System.Runtime.CompilerServices.Extension()> _
Public Function Compose(Of T)(ByVal first As Expressions.Expression(Of T), ByVal second As Expressions.Expression(Of T), ByVal merge As Func(Of Expressions.Expression, Expressions.Expression, Expressions.Expression)) As Expressions.Expression(Of T)
'' build parameter map (from parameters of second to parameters of first)
Dim map = first.Parameters.[Select](Function(f, i) New With {f, .s = second.Parameters(i)}).ToDictionary(Function(p) p.s, Function(p) p.f)
'' replace parameters in the second lambda expression with parameters from the first
Dim secondBody = ParameterRebinder.ReplaceParameters(map, second.Body)
'' applycomposition of lambda expression bodies to parameters from the first expression
Return Expressions.Expression.Lambda(Of T)(merge(first.Body, secondBody), first.Parameters)
End Function
<System.Runtime.CompilerServices.Extension()> _
Public Function [And](Of T)(ByVal first As Expressions.Expression(Of Func(Of T, Boolean)), ByVal second As Expressions.Expression(Of Func(Of T, Boolean))) As Expressions.Expression(Of Func(Of T, Boolean))
Return first.Compose(second, AddressOf Expressions.Expression.And)
End Function
然後你就可以建立查詢是這樣的:
Dim MyQuery as Linq.Expressions.Expression(Of System.Func(Of MyListDataType, Boolean))
Dim MyGroupingExpression as Linq.Expressions.Expression(Of System.Func(Of MyListDataType, Boolean))
Dim MyQuery = Function(x) x.SomeValue = SomeExpectedValue
Select case SomeOtherVariable
Case Option1
Dim MyGroupingExpression = <blah>
Case Option2
Dim MyGroupingExpression = <blah>
End Select
Dim Results = MyList.Where(MyQuery.And(GroupingExpression))
這是你在做什麼後?
謝謝Tim!將測試和確認,但看起來像我正在尋找。 – code4life 2010-08-13 16:06:51