开发者

Searching by regexp when constructing LINQ expression using Expression classes

开发者 https://www.devze.com 2023-04-08 04:23 出处:网络
Here is the post which describes the way to create an Expression<Func<MyClass, bool>> predicate dynamically. Here is a snippet:

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

精彩评论

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

关注公众号