Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda and Expression.Call for an extension method

I need to implement an expression for a method like here:

var prop = Expression.Property(someItem, "Name"); 
var value = Expression.Constant(someConstant);

var contains = typeof(string).GetMethod("Contains", new[] {typeof(string)});
var expression = Expression.Call(prop, contains, value);

But for my extension method:

public static class StringEx
{
    public static bool Like(this string a, string b)
    {
        return a.ToLower().Contains(b.ToLower());
    }
}

Unfortunately, next code throws an ArgumentNullException for a parameter "method":

var like = typeof(string).GetMethod("Like", new[] {typeof(string)});
comparer = Expression.Call(prop, like, value);

What I'm doing wrong?

like image 709
CodeAddicted Avatar asked Dec 01 '11 07:12

CodeAddicted


2 Answers

Try this

public class Person
{
    public string Name { get; set; }
}
public static class StringEx
{
    public static bool Like(this string a, string b)
    {
        return a.ToLower().Contains(b.ToLower());
    }
}

Person p = new Person(){Name = "Me"};
var prop = Expression.Property(Expression.Constant(p), "Name");
var value = Expression.Constant("me");
var like = typeof(StringEx).GetMethod("Like", BindingFlags.Static
                        | BindingFlags.Public | BindingFlags.NonPublic);
var comparer = Expression.Call(null, like, prop, value );

var vvv = (Func<bool>) Expression.Lambda(comparer).Compile();
bool isEquals = vvv.Invoke();
like image 99
Lonli-Lokli Avatar answered Sep 27 '22 23:09

Lonli-Lokli


You can do like this:

var like = typeof(StringEx).GetMethod("Like", new[] {typeof(string), typeof(string)});

comparer = Expression.Call(null, like, prop, value);

You can pass prop as first parameter and value as second parameter like above.

Maybe you will need to get a complete query before apply an extension method.

like image 25
Austin Felipe Avatar answered Sep 28 '22 00:09

Austin Felipe