目前,我有這種方法來比較兩個數字
Private Function ETForGreaterThan(ByVal query As IQueryable(Of T), ByVal propertyValue As Object, ByVal propertyInfo As PropertyInfo) As IQueryable(Of T)
Dim e As ParameterExpression = Expression.Parameter(GetType(T), "e")
Dim m As MemberExpression = Expression.MakeMemberAccess(e, propertyInfo)
Dim c As ConstantExpression = Expression.Constant(propertyValue, propertyValue.GetType())
Dim b As BinaryExpression = Expression.GreaterThan(m, c)
Dim lambda As Expression(Of Func(Of T, Boolean)) = Expression.Lambda(Of Func(Of T, Boolean))(b, e)
Return query.Where(lambda)
End Function
它工作正常,並以這種方式消費
query = ETForGreaterThan(query, Value, propertyInfo)
正如您所看到的,我給它一個IQueryable集合,並根據屬性和值為它添加一個where子句。 Y可以構造Lessthan,LessOrEqualThan等等System.Linq.Expressions.Expression預定義此運算符。
Â?我如何轉換此代碼以對字符串執行相同操作? System.Linq.Expressions.Expression不給我一個預定義的運算符,如“contains”或“startwith”,我真的是表達樹的noob。
謝謝,請在C#/ VB中發布您的答案。選擇讓您感覺更舒適的那個。
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace WindowsFormsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
using (var context = new NorthwindEntities())
{
PropertyInfo propertyInfo = typeof(Customer).GetProperty("CustomerID");
IQueryable<Customer> query = context.Customers;
query = ETForStartsWith<Customer>(query, "A", propertyInfo);
var list = query.ToList();
}
}
static IQueryable<T> ETForStartsWith<T>(IQueryable<T> query, string propertyValue, PropertyInfo propertyInfo)
{
ParameterExpression e = Expression.Parameter(typeof(T), "e");
MemberExpression m = Expression.MakeMemberAccess(e, propertyInfo);
ConstantExpression c = Expression.Constant(propertyValue, typeof(string));
MethodInfo mi = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
Expression call = Expression.Call(m, mi, c);
Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(call, e);
return query.Where(lambda);
}
}
}
它不是一個運算符,而是一個方法,因此您可以使用Expression.Call()調用它,其中methodinfo參數將是typeof(string).GetMethod(“StartsWith”)。