我的情况与此类似:How to declare a Linq Expression variable in order to have it processed as a dbParameter
但就我而言,不要与“平等”相提并论。运算符,我需要比较一个字符串与另一个字符串。我怎样才能做到这一点?
我试过这样的事情:
struct Plant: Codable {
let date: Date
let monthlyAVG: String?
enum CodingKeys : String, CodingKey {
case date = "Date"
case monthlyAVG = "30_Day_MA_MMBTU"
}
}
但遗憾的是,字符串不支持GreaterThanOrEqual。所以我需要string.CompareTo(..)方法,至少SQL支持实体。
说:
do {
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd"
decoder.dateDecodingStrategy = .formatted(formatter)
let plantData = try decoder.decode([Plant].self, from: data)
.filter { $0.monthlyAVG != nil }
print(plantData)
} catch let parseError {
print(parseError)
}
如何以编译器可以理解的方式编写它?
任何帮助都是相关的。 谢谢!
答案 0 :(得分:1)
如果您调查
的编译器翻译Expression<Func<string, bool>> f = s => s.CompareTo("aaaa") >= 0;
你会发现你需要使用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);