我有一个相对简单的LINQ表达式,我需要将其转换为VB表达式树语法。对于熟悉的人来说,这可能是一件容易的事,但我是LINQ表达树领域的新手。
在我的示例中,您会看到“New Int16(){}”数组。该值必须在运行时使用另一个代码元素的值数组进行参数化。
我的查询是:
from i in tblInstitutions
let ChildHasCategory = i.tblInstCtgyHistories.Where(Function(CtgyHist) CtgyHist.EndDate is Nothing AND ( (New Int16() {32,35,38,34}).Contains(CtgyHist.InstCtgyCodeFK)))
where ChildHasCategory.Any()
select i
其中也可以表示为:
tblInstitutions
.Select (i => new {
i = i,
ChildHasCategory = (IEnumerable<tblInstCtgyHistory>)(i.tblInstCtgyHistories)
.Where (
CtgyHist =>
((CtgyHist.EndDate == null) &
(IEnumerable<Int16>)(new Int16[] { 32, 35, 38, 34 } ).Contains (CtgyHist.InstCtgyCodeFK)
)
)
}
)
.Where ($VB$It => $VB$It.ChildHasCategory.Any ())
.Select ($VB$It => $VB$It.i)
这将在ASP.NET动态数据Web应用程序中的自定义筛选器的上下文中使用。我想模仿默认方法。 其他动态过滤器代码隐藏的示例之一是:
Public Overrides Function GetQueryable(source As IQueryable) As IQueryable
Dim value = TextBox1.Text
If String.IsNullOrWhiteSpace(value) Then
Return source
End If
If DefaultValues IsNot Nothing Then
DefaultValues(Column.Name) = value
End If
Dim parameter = Expression.Parameter(source.ElementType)
Dim columnProperty = Expression.PropertyOrField(parameter, Column.Name)
Dim likeValue = Expression.Constant(value, GetType(String))
Dim condition = Expression.Call(columnProperty, GetType(String).GetMethod("Contains"), likeValue)
Dim where = Expression.Call(GetType(Queryable), "Where", New Type() {source.ElementType}, source.Expression, Expression.Lambda(condition, parameter))
Return source.Provider.CreateQuery(where)
End Function
答案 0 :(得分:2)
我不确定你真的需要担心这里的表达树。首先,我们应该能够如下表达您的查询:
Dim targetCodes = new Int16() {32, 35, 38, 34 } ' This could be data driven as well
return from i in tblInstitutions
where i.tblInstCtgyHistories.Any(Function(ctgyHist) ctgyHist.EndDate is Nothing AndAlso
targetCodes.Contains(ctgyHist.InstCtgyCodeFK))
select i
鉴于此,在什么情况下你需要自定义表达式树?