问题描述
我创建了一个可过滤的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();
例如
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< Expression,Expression,Expression>
:
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为Like?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!