Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a generic extension method to provide filtering functionality

I'm working on an extension method to provide filtering capabilities for several entities. The entities involved are of different types but have common fields that can be searched on.

The below is working at the moment, however I was wondering if this could be "genericized" so that the casting from generic to explicit type doesn't need to occur?

public static IQueryable<T> PriceLow<T>(this IQueryable<T> query, decimal? priceLow)
{
    if (typeof(T) == typeof(Entity1))
    {
        var innerQuery = (IQueryable<Entity1>) query;
        var results = priceLow.HasValue ? innerQuery.Where(o => (o.ListPrice > priceLow.Value)) : innerQuery;
        return (IQueryable<T>) results;
    }

    if (typeof(T) == typeof(Entity2))
    {
        var innerQuery = (IQueryable<Entity2>)query;
        var results = priceLow.HasValue ? innerQuery.Where(o => (o.ListPrice > priceLow.Value)) : innerQuery;
        return (IQueryable<T>)results;
    }

    return null;
}

Example usage:

    var foo = _repository.GetAllEntity1().PriceLow(_searchCritera.PriceLow);
like image 733
Jesse Avatar asked Jun 30 '26 13:06

Jesse


2 Answers

If you can change the two entity types to implement a common interface which has the shared properties/methods, then you can use a generic type constraint. This would also work with a shared base class.

Do that, and then your signature looks like this (cluttering details omitted):

public static IQueryable<T> PriceLow<T>(...)
  where T : ICommonInterface
like image 111
Paul Phillips Avatar answered Jul 02 '26 04:07

Paul Phillips


How about making your entities inherit from a base type that holds the searchable fields. That way your filter method only needs to know about the one base type.

like image 43
AUSteve Avatar answered Jul 02 '26 03:07

AUSteve