L
L
lucky42021-04-12 10:42:02
C++ / C#
lucky4, 2021-04-12 10:42:02

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);
        }


ApplySearching -> I would do it like this if I did it directly through some service controller: where(x=>x.propNAME == "xxx"). But in this generic function I have an error => "System.Linq.Expressions.Expression>' to 'System.Func'"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
cicatrix, 2021-04-12
@lucky4

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));
}

The only negative is that the objects that are being filtered will have to implement the IMyItem interface.
In the IsMatch method, accordingly, a check should be performed whether the object matches the search string or not.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question