自定义表达
我找到了这个示例代码:
public IQueryable<T> Get<T>(ObjectSet<T> obj) where T : class
{
Type type = typeof(T);
var x = type.GetInterface("IMyInterface");
if (x != null)
{
var property = type.GetProperty("MyStringField");
var parameter = Expression.Parameter(typeof(T), "it");
Expression<Func<T, bool>> predicate =
(Expression<Func<T, bool>>)Expression.Lambda(
Expression.Equal(
Expression.MakeMemberAccess(parameter, property),
Expression.Constant("MyValue")),
parameter);
//...
}
}
我真正需要的是应用 StartsWith 条件 (StartsWith("MyValue")
) 并为我的另一个 int?
应用另一个条件,例如 >= > 财产。
我该如何修改代码来做到这一点?
I found this example code:
public IQueryable<T> Get<T>(ObjectSet<T> obj) where T : class
{
Type type = typeof(T);
var x = type.GetInterface("IMyInterface");
if (x != null)
{
var property = type.GetProperty("MyStringField");
var parameter = Expression.Parameter(typeof(T), "it");
Expression<Func<T, bool>> predicate =
(Expression<Func<T, bool>>)Expression.Lambda(
Expression.Equal(
Expression.MakeMemberAccess(parameter, property),
Expression.Constant("MyValue")),
parameter);
//...
}
}
What I really need is to apply a StartsWith condition (StartsWith("MyValue")
) and apply another condition like >= for my another int?
property.
How can I modify the code to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,考虑一下这个表达式树代表什么表达式。
相当于 lambda:
那么您希望表达式是什么?根据我的理解,你写的,你想要这样的东西:
好吧,你可以编写这个 lambda 并将其存储在一个表达式中,这样你就可以让编译器为你执行转换:
否则,手动执行:
First of all, consider what expression this expression tree represents.
is equivalent to the lambda:
So what would you like the expression be then? From what I understand you wrote, you want something like this:
Well you can write this lambda and store it in an expression that way you can let the compiler perform the conversion for you:
Otherwise, doing it by hand: