我正忙于在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))
初始化了我的表达体。在我看来,应该有更好的方式...
如何?