0
我想要構建一個表達式樹,其行爲就像在SQL中一樣。也就是說,我希望它忽略字符串例如: - 的情況下我需要使用表達式樹來搜索字符串,忽略字符串的大小寫
"ThIs Is A tEsT"
,"tHiS iS a TeSt"
,"this is a test"
,並且"THIS IS A TEST"
都應該匹配"this is a test"
。
我試了幾件事情,似乎沒有任何工作。
我想要構建一個表達式樹,其行爲就像在SQL中一樣。也就是說,我希望它忽略字符串例如: - 的情況下我需要使用表達式樹來搜索字符串,忽略字符串的大小寫
"ThIs Is A tEsT"
,"tHiS iS a TeSt"
,"this is a test"
,並且"THIS IS A TEST"
都應該匹配"this is a test"
。
我試了幾件事情,似乎沒有任何工作。
我找到了最直接的方式來完成這項任務是調用這樣一個自定義的方法:
public class Datum
{
public string Value { get; set; }
}
void Main()
{
var data = new List<Datum> {
new Datum { Value = "ThIs Is A tEsT" },
new Datum { Value = "tHiS iS a TeSt" },
new Datum { Value = "this is a test" },
new Datum { Value = "THIS IS A TEST" }
};
var queryableData = data.AsQueryable<Datum>();
var pe = Expression.Parameter(typeof(Datum), "Value");
var right = Expression.Constant("this is a test", typeof(string));
// * First build a func that will use the method you want. In this case, it is going to be any equals that ignores case.
// * Next Invoke that method instead of Expression.Equal.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Expression<Func<string, string, bool>> IgnoreCase = (op1, op2) => op1.Equals(op2, StringComparison.OrdinalIgnoreCase);
var e = Expression.Invoke(IgnoreCase, Expression.Property(pe, "Value"), right);
//var e = Expression.Equal(Expression.Property(pe, "Value"), right);
var whereCallExpression = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { queryableData.ElementType },
queryableData.Expression,
Expression.Lambda<Func<Datum, bool>>(e, pe));
var results = queryableData.Provider.CreateQuery<Datum>(whereCallExpression);
results.Dump();
}