using System.Linq.Expressions;
public static class QueryableExtensions
{
public static IQueryable ApplyFilters(this IQueryable query, T filter) where T : class
{
var isFilterApplied = false;
var parameter = Expression.Parameter(typeof(T), “x”);
Expression combined = null;
foreach (var property in typeof(T).GetProperties())
{
var value = property.GetValue(filter);
if (value != null)
{
var member = Expression.Property(parameter, property.Name);
var constant = Expression.Constant(value);
Expression expression = null;
if (property.PropertyType == typeof(string))
{
var toUpperMethod = typeof(string).GetMethod("ToUpper", Type.EmptyTypes);
var containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
expression = Expression.Call(
Expression.Call(member, toUpperMethod),
containsMethod,
Expression.Call(constant, toUpperMethod)
);
}
else if (property.PropertyType == typeof(int))
{
expression = Expression.Equal(member, constant);
}
else if (property.PropertyType == typeof(bool?))
{
expression = Expression.Equal(member, constant);
}
else if (property.PropertyType == typeof(DateTime?))
{
expression = Expression.Equal(member, constant);
}
else
{
expression = Expression.Equal(member, constant);
}
if (combined == null)
{
combined = expression;
}
else
{
combined = Expression.AndAlso(combined, expression);
}
isFilterApplied = true;
}
}
if (isFilterApplied && combined != null)
{
var lambda = Expression.Lambda<Func<T, bool>>(combined, parameter);
query = query.Where(lambda);
}
return query;
}
}
Gostaria de aplicar boas praticas
New contributor
Luize dhx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.