I'm trying to dynamically generate the following expression
x => x?.ToLower().Contains(value?.ToLower())
on my Item class.
Here is my Item class:
public class Item
{
public string? Type { get; set; }
}
I was able to do a NULL check and Contains call using the following code.
var param = Expression.Parameter(typeof(Item), "i");
MethodInfo containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var itemTypeMember = Expression.Property(param, "Type");
var itemTypeNullCheck = Expression.Equal(itemTypeMember, Expression.Constant(null));
var itemTypeConstant = Expression.Constant(itemType, typeof(string));
var itemTypeBody = Expression.Call(itemTypeMember, containsMethod, itemTypeConstant);
var itemTypeCondition = Expression.Condition(itemTypeNullCheck, Expression.Constant(false), itemTypeBody);
var lambda = Expression.Lambda<Func<Item, bool>>(itemTypeCondition, param);
Query.Where(lambda);
So far so good. This works as expected. And I achieved till
x => x?.Contains(value)
But the problem with this is that it is not case insensitive comparison.
Now when I try to add ToLower() with above code,
MethodInfo toLowerMethod = typeof(string).GetMethod("ToLower", new[] { typeof(string) });
var itemTypeBody = Expression.Call(Expression.Call(itemTypeMember, toLowerMethod), containsMethod, itemTypeConstant);
I get the following error.
Value cannot be null. (Parameter 'method')
System.ArgumentNullException: Value cannot be null. (Parameter 'method')
at System.ArgumentNullException.Throw(String paramName)
at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method)
Please assist me on what I'm missing.
There's no
ToLowermethod onstringthat accepts astringargument.thisdoesn't count: