我创建了一个可过滤的BindingList from this source。效果很好:
list.Filter("Customer == 'Name'");
做它应该做的。内部结构就像解析器一样,将表达式
==
或!=
转换为System.Linq.Expressions.Expression
。在这种情况下,==
变为System.Linq.Expressions.Expression.Equal
。不幸的是,
System.Linq.Expressions.Expression
不包含like运算符,而且我不知道该如何解决。初始代码如下所示:
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);
}
然后,我创建了一个表达式,可以执行我想要的操作:
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>
预定义的表达式似乎恰好是:
System.Linq.Expressions.Expression.Or;
谁能告诉我如何转换我的表情?
最佳答案
就像是:
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);
}
关于c# - 如何为Like创建System.Linq.Expressions.Expression?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/956743/