-1

I have similar Situation like here: How to declare a Linq Expression variable in order to have it processed as a dbParameter

But in my case, don't want to compare with 'equal' operator, I need to compare one string against another. How can I achieve this?

I tried something like this:

    var comparsionString = "aaa";
    ParameterExpression param = Expression.Parameter(typeof(ItemSearch), "s");
    Expression prop = Expression.Property(param, "Id");
    Expression<Func<string>> idLambda = () => comparsionString;
    Expression searchExpr = Expression.GreaterThanOrEqual(prop, idLambda.Body);

    Expression<Func<ItemSearch, bool>> myLambda =
        Expression.Lambda<Func<ItemSearch, bool>>(searchExpr, param);

But unfortunately GreaterThanOrEqual is not supported for strings. So I would need the string.CompareTo(..) method which is supported at least by SQL to Entities.

Say:

Expression searchExpr = Expression.IsTrue(*prop*.CompareTo(*idLambda*) >= 0);

How to write this in a way, that compiler can understand?

Any help is apreciated. Thank you!

user1470240
  • 580
  • 3
  • 19
  • 1
    Can this answer help? https://stackoverflow.com/a/24890249/4222487 – FaizanHussainRabbani Feb 23 '18 at 18:28
  • 1
    You can use LINQPad to output `Expression` variables that you initialize to something similar to your desired output and then write the code to re-create it. Nice use of `idLambda`, but an `Expression.Constant` might be better. – NetMage Feb 23 '18 at 22:18

1 Answers1

1

If you investigate the compiler translation for

Expression<Func<string, bool>> f = s => s.CompareTo("aaaa") >= 0;

You will discover you need to use GreaterThanOrEqual(Call("s", "CompareTo", "aaaa")) so the code to create that is:

var comparsionString = "aaa";
ParameterExpression param = Expression.Parameter(typeof(ItemSearch), "s");
Expression prop = Expression.Property(param, "Id");
Expression<Func<string>> idLambda = () => comparsionString;
var CallMethod = typeof(string).GetMethod("CompareTo", new[] { typeof(string) });
Expression callExpr = Expression.Call(prop, CallMethod, idLambda.Body);
Expression searchExpr = Expression.GreaterThanOrEqual(callExpr, Expression.Constant(0));

Expression<Func<ItemSearch, bool>> myLambda =
    Expression.Lambda<Func<ItemSearch, bool>>(searchExpr, param);
NetMage
  • 26,163
  • 3
  • 34
  • 55