下面的代码可以使用StartsWith
,Contains
但是当我尝试时,Equals
我得到了这个异常:'System.String' 类型上的多个方法 'Equals' 与提供的参数兼容。
要恢复, CreatePredicate 可以构建 3 种类型的谓词,但只有以下Equals
不起作用:
AList.Where(x => x.MyField.StartsWith("ValueToSearch")); //OK
AList.Where(x => x.MyField.Contains("ValueToSearch")); //OK
AList.Where(x => x.MyField.Equals("ValueToSearch")); //Not OK
..
public enum TypeSearch
{
StartsWith = 1,
Contains = 2,
Equals = 3
}
private static Expression<Func<T, bool>> CreatePredicate<T>(string member, object value, TypeSearch type)
{
var p = System.Linq.Expressions.Expression.Parameter(typeof(T));
System.Linq.Expressions.Expression body = p;
foreach (var subMember in member.Split('.'))
{
body = System.Linq.Expressions.Expression.PropertyOrField(body, subMember);
}
var res = System.Linq.Expressions.Expression.Lambda<Func<T, bool>>(
System.Linq.Expressions.Expression.Call(
System.Linq.Expressions.Expression.Call(
body,
"ToUpper", null),
type.ToString(), null,
System.Linq.Expressions.Expression.Constant(value.ToString().ToUpper())
), p);
return res;
}