Answer the question
In order to leave comments, you need to log in
How to write a generalized filter?
I do pagination and filtering for the apishka. Unfortunately, I did not want to use this option, with the work of generalized queries, but out of desperation I have to write something that is not entirely clear to me personally. Somehow, I found options and adjusted it for myself for "sorting by", but now the problem is "search by":
public static Expression<Func<T, object>> ToLambda<T>(string propertyName)
{
var parametr = Expression.Parameter(typeof(T));
var property = Expression.Property(parametr, propertyName);
var propObject = Expression.Convert(property, typeof(object));
return Expression.Lambda<Func<T, object>>(propObject, parametr);
}
public static IQueryable<T> ApplyOrdering<T>(this IQueryable<T> source,
string propertyName, bool desc = false)
{
return desc != true ?
source.OrderBy(ToLambda<T>(propertyName))
: source.OrderByDescending(ToLambda<T>(propertyName));
}
public static IQueryable<T> ApplySearching<T>(this IQueryable<T> source,
string propertyName, string input)
{
return source.Where(ToLambda<T>(propertyName) == input);
}
Answer the question
In order to leave comments, you need to log in
In this example, the string is compared with Func.
I would do like this:
public interface IMyItem
{
bool IsMatch(string pattern);
}
public static IQueryable<T> ApplyFilter<T>(this IQueryable<T> source, string filtertext) where T: IMyItem
{
return source.Where(item => item.IsMatch(filtertext));
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question