开发者

Searching by regexp when constructing LINQ expression using Expression classes

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);
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜