使用Expression类构造LINQ表达式时使用regexp进行搜索

时间:2011-09-27 09:17:01

标签: c# .net lambda

Here是描述动态创建Expression<Func<MyClass, bool>>谓词的方法的帖子。这是一个片段:

 var param = Expression.Parameter(typeof(string), "p");
    var len = Expression.PropertyOrField(param, "SomeText");
    var body = Expression.Equal(
        len, Expression.Constant("Text"));

    var lambda = Expression.Lambda<Func<string, bool>>(
        body, param);

我想知道如何将regexp应用于字符串而不是Equality。有可能吗? 可能的伪代码如下:

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

1 个答案:

答案 0 :(得分:1)

您可以使用Expression.Call(Type type, string methodName, Type[] typeArguments, params Expression[] arguments)来调用检查正则表达式的测试方法。

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