我正忙于在 IQueryable Linq 对象上编写动态 AND 过滤器,到目前为止,这是我的代码,它可以工作:
public static IQueryable<T> FilterHeaders<T>(this IQueryable<T> records, IEnumerable<ListHeader> headers)
{
// Build linq expression to filter queryable
if (headers != null)
{
var param = Expression.Parameter(typeof(T), "x");
var body = Expression.And(Expression.Constant(true), Expression.Constant(true));
foreach (var header in headers)
{
if (header.Filter != null && !String.IsNullOrWhiteSpace(header.Filter.Value))
{
var property = Expression.PropertyOrField(param, header.HeaderType.ToString());
var value = Expression.Constant(header.Filter.Value.Trim(), typeof(string));
body = Expression.AndAlso(body, Expression.Call(property, "Contains", null, value));
}
}
var lambda = Expression.Lambda<Func<T, bool>>(body, param);
return records.Where(lambda);
}
return records;
}
我已经用Expression.And(Expression.Constant(true), Expression.Constant(true))
. 在我看来,应该有更好的方法......
如何?