Jerkylink
Jerkylink

Reputation: 3

grouping to generic method in Repository EF C#

I tried to group in a generic method, but the way I try it gives me the following error:

The type arguments for method 'System.Linq.Enumerable.OrderBy (System.Collections.Generic.IEnumerable , System.Func )' can not be inferred from the usage. Try specifying the type arguments explicitly.

Removing the group by the method works correctly, the only thing I lack is to make it can group.

public List<T> FilterPagerGroup<T, TType>(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, T>> select, int skip, int take, Expression<Func<TEntity, TType>> orderBy, Expression<Func<TEntity, TType>> groupBy)
    {
        List<T> result;

        result = EntitySet.Where(where).GroupBy(groupBy).OrderBy(orderBy).Skip(skip).Take(take).Select(select).ToList();

        return result;
    }

Upvotes: 0

Views: 1048

Answers (1)

Rob
Rob

Reputation: 27357

You're grouping your collection, so you no longer have an IQueryable<TEntity>, you have IQueryable<IGrouping<TType, TEntity>>. You'll need to update your select and orderBy types to properly reflect what you're doing. Here's a working example:

public class Thing<TEntity>
{
    public IQueryable<TEntity> EntitySet = new TEntity[0].AsQueryable();
    public List<T> FilterPagerGroup<T, TType>(
        Expression<Func<TEntity, bool>> where,
        Expression<Func<IGrouping<TType, TEntity>, T>> select, int skip, int take,
        Expression<Func<IGrouping<TType, TEntity>, TType>> orderBy,
        Expression<Func<TEntity, TType>> groupBy)
    {
        List<T> result;

        result = EntitySet.Where(where).GroupBy(groupBy).OrderBy(orderBy).Skip(skip).Take(take).Select(select).ToList();

        return result;
    }
}

Note that the caller of this method will also need to be updated to operate on an IGrouping<TType, TEntity> rather than simply TEntity.

Upvotes: 2

Related Questions