如何在c#中使用DynamicFilterBuilder基于包含进行搜索



在我的项目目前,我已经实现了多次搜索使用下面的功能代码:

public static IQueryable<T> Filter<T>(this IQueryable<T> source, SearchCriteria searchCriteria)
{
var predicate = new DynamicFilterBuilder<T>();
foreach (var item in searchCriteria.filters)
{
if (!string.IsNullOrEmpty(item.key))
{
if (item.key == "CreatedOn")
predicate.And(item.key, DynamicExpressions.FilterOperator.GreaterThanOrEqual, DateTime.ParseExact(item.value.ToString() + " 00:00:00", "yyyy-MM-dd HH:mm:ss", null))
.And(item.key, DynamicExpressions.FilterOperator.LessThanOrEqual, DateTime.ParseExact(item.value.ToString() + " 23:59:59", "yyyy-MM-dd HH:mm:ss", null));
else
predicate.And(item.key,
DynamicExpressions.FilterOperator.Contains, item.value);
}
}
return source.Where(predicate.Build());
}

但是它的工作只是像大小写敏感意味着我需要传递确切的名称ex: "Data"如果我传递了&;data&;它没有返回任何东西,所以有人能帮我吗?

您可以在这里进行小写转换,并与下面的小写字母进行比较:

if (item.key.ToLower() == "createdon")
{
//Your stuff
}

评论中提到的zHaytam包(github.com/zHaytam/DynamicExpressions)在GitHub上是开源的,所以我们可以看到在它的实现(class DynamicExpressions)中,表达式被委托给Linq表达式:

private static Expression CreateFilter(MemberExpression prop, FilterOperator op, ConstantExpression constant)
{
return op switch
{
FilterOperator.Equals => Expression.Equal(prop, constant),
FilterOperator.GreaterThan => Expression.GreaterThan(prop, constant),
FilterOperator.LessThan => Expression.LessThan(prop, constant),
FilterOperator.Contains => Expression.Call(prop, _containsMethod, PrepareConstant(constant)),
FilterOperator.StartsWith => Expression.Call(prop, _startsWithMethod, PrepareConstant(constant)),
FilterOperator.EndsWith => Expression.Call(prop, _endsWithMethod, PrepareConstant(constant)),
FilterOperator.DoesntEqual => Expression.NotEqual(prop, constant),
FilterOperator.GreaterThanOrEqual => Expression.GreaterThanOrEqual(prop, constant),
FilterOperator.LessThanOrEqual => Expression.LessThanOrEqual(prop, constant),
_ => throw new NotImplementedException()
};
}

containsMethod使用string.Containspublic bool Contains (string value);版本:

private static readonly MethodInfo _containsMethod = typeof(string).GetMethod("Contains"
, new Type[] { typeof(string) });

使"Contains"方法变得不区分大小写,我想你可以下载并修改zHaytam的代码:

方法DynamicExpressions修改_containsMethod的初始化表达式以引用string.Containspublic bool Contains (string value, StringComparison comparisonType)版本:

private static readonly MethodInfo _containsMethod = typeof(string).GetMethod("Contains"
, new Type[] { typeof(string), typeof(StringComparison) });

并修改CreateFilter方法以提供忽略大小写的附加参数:

FilterOperator.Contains => Expression.Call(prop, _containsMethod, PrepareConstant(constant), Expression.Constant(StringComparison.OrdinalIgnoreCase)),

相关内容

  • 没有找到相关文章

最新更新