[英]c# How to evaluate compareTo(..) in Expression which returns a string
I have similar Situation like here: How to declare a Linq Expression variable in order to have it processed as a dbParameter我有类似的情况: 如何声明 Linq 表达式变量以便将其作为 dbParameter 处理
But in my case, don't want to compare with 'equal' operator, I need to compare one string against another.但在我的情况下,不想与 'equal' 运算符进行比较,我需要将一个字符串与另一个字符串进行比较。 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.但不幸的是,字符串不支持 GreaterThanOrEqual。 So I would need the string.CompareTo(..) method which is supported at least by SQL to Entities.
所以我需要至少由 SQL to Entities 支持的 string.CompareTo(..) 方法。
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!
谢谢!
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:你会发现你需要使用 GreaterThanOrEqual(Call("s", "CompareTo", "aaaa")) 所以创建它的代码是:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.