Here is the post which describes the way to create an Expression<Func<MyClass, bool>>
predicate dynamically. Here is a snippet:
var param = Expression.Parameter(typeof(string), "p");
var len = Expression.PropertyOrField(param, "SomeText");
var body = Expression.Equal(
len, Expression.Constant("Text"));
var lambda = Exp开发者_如何学Cression.Lambda<Func<string, bool>>(
body, param);
I wonder how do I apply a regexp to a string instead of Equality. Is there a possibility? A possible pseudo code would be like:
var param = Expression.Parameter(typeof(string), "p");
var len = Expression.PropertyOrField(param, "SomeText");
var body = Expression.Regexp(
len, @"\D+");
var lambda = Expression.Lambda<Func<string, bool>>(
body, param);
You can use Expression.Call(Type type, string methodName, Type[] typeArguments, params Expression[] arguments)
to call your test method that checks for regular expression.
List<string> lista = new List<string>() { "aaaa", "aaabb", "aaacccc", "eee" };
var param = Expression.Parameter(typeof(string), "s");
var pattern = Expression.Constant("\\Aa");
var test = Expression.Call(typeof(Regex), "IsMatch", null, param, pattern);
var lambda = Expression.Lambda<Func<string, bool>>(test, param);
IEnumerable<string> query = lista.Where(lambda.Compile());
foreach (string s in query)
{
Console.WriteLine(s);
}
精彩评论