There are a few problems with your code
Expression<TDelegate>
is a class, so it's nullable already; you can simply test iforderBy == null
.Nullable<T>
has a generic constraint thatT
must be astruct
, soExpression<Func<MyObject, T>>?
won't compile.- Next you'll have the problem that because the type
T
isn't bound inside the method, butx.Id
is. In other words, you won't be able to create use the conditional operator to choose between a value ofExpression<Func<MyObject, T>>
andExpression<Func<MyObject, int>>
(assuming thatId
is anint
) while still maintaining type information to pass to theOrderBy
method.
The solution is to use something along these lines:
public IPagedList<MyObject> GetAll<T>(Expression<Func<MyObject, T>> orderBy,
int pageNumber = 1, int pageSize = 10)
{
IQueryable<MyObject> objects = dataContext.MyObjects;
objects = (orderBy != null) ? objects.OrderBy(orderBy)
: objects.OrderBy(x => x.Id);
return objects.ToPagedList<MyObject>(pageNumber, pageSize);
}
The conditional operator works in this code because regardless of what you pass to OrderBy
the return type will be the same, IQueryable<MyObject>
.
Note also that you can't simply pass in a null value for orderBy
, because T
can't be inferred. You'd have to call it like this:
var results = MyClass.GetAll<int>(null);
Ultimately, you'd probably be better off creating two overloads, one that accepts an orderBy
expression, and one that doesn't.