问题描述
我创建了一个过滤的BindingList的>。它的伟大工程:
I created a filterable BindingList from this source. It works great:
list.Filter("Customer == 'Name'");
做什么它应该。该内部工作就像一个分析器,可以转换表达 ==
或!=
到系统.Linq.Expressions.Expression
。在这种情况下, ==
变成 System.Linq.Expressions.Expression.Equal
。
does what it should. The internals work like a parser, that converts the expression ==
or !=
into System.Linq.Expressions.Expression
. In this case, ==
becomes System.Linq.Expressions.Expression.Equal
.
不幸的是 System.Linq.Expressions.Expression
不包含运营商一样,我不知道如何解决这个问题。
Unfortunately System.Linq.Expressions.Expression
does not contain a like operator and I don't know how to solve this.
最初的代码如下所示:
private static Dictionary<String, Func<Expression, Expression, Expression>>
binaryOpFactory = new Dictionary<String, Func<Expression, Expression, Expression>>();
static Init() {
binaryOpFactory.Add("==", Expression.Equal);
binaryOpFactory.Add(">", Expression.GreaterThan);
binaryOpFactory.Add("<", Expression.LessThan);
binaryOpFactory.Add(">=", Expression.GreaterThanOrEqual);
binaryOpFactory.Add("<=", Expression.LessThanOrEqual);
binaryOpFactory.Add("!=", Expression.NotEqual);
binaryOpFactory.Add("&&", Expression.And);
binaryOpFactory.Add("||", Expression.Or);
}
然后,我创建了一个会做我想做的表达式:
Then I created an expression that will do what I want:
private static System.Linq.Expressions.Expression<Func<String, String, bool>>
Like_Lambda = (item, search) => item.ToLower().Contains(search.ToLower());
private static Func<String, String, bool> Like = Like_Lambda.Compile();
例如
e.g.
Console.WriteLine(like("McDonalds", "donAld")); // true
Console.WriteLine(like("McDonalds", "King")); // false
但 binaryOpFactory
需要此:
Func<Expression, Expression, Expression>
预定义的表情似乎正是:
The predefined expressions seem to be exactly that:
System.Linq.Expressions.Expression.Or;
谁能告诉我怎么我的表情转换?
Can anyone tell me how to convert my expression?
推荐答案
是这样的:
static IEnumerable<T> WhereLike<T>(
this IEnumerable<T> data,
string propertyOrFieldName,
string value)
{
var param = Expression.Parameter(typeof(T), "x");
var body = Expression.Call(
typeof(Program).GetMethod("Like",
BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public),
Expression.PropertyOrField(param, propertyOrFieldName),
Expression.Constant(value, typeof(string)));
var lambda = Expression.Lambda<Func<T, bool>>(body, param);
return data.Where(lambda.Compile());
}
static bool Like(string a, string b) {
return a.Contains(b); // just for illustration
}
在 Func键和LT而言,表达,表达,表达>
:
static Expression Like(Expression lhs, Expression rhs)
{
return Expression.Call(
typeof(Program).GetMethod("Like",
BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)
,lhs,rhs);
}
这篇关于如何创建像System.Linq.Expressions.Expression?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!