A common method for ordering strings is parsing an expression

I end up writing a lot of code that looks like

var ordered = isDescending ? queryable.OrderByDescending(x => x.ID) : queryable.OrderBy(x => x.ID)

      

but with different expressions like x => x.DateOfBirth etc. What I would like to do is place this in a generic extension method so that I can parse my expression, and the isDescending to boolean, but I'm not sure how. Something like

public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, Expression<Func<T, TKey>> func, bool isDescending) {
  return isDescending ? source.OrderByDescending(func) : source.OrderBy(func);
}

      

Can anyone tell me how to do this? It is desirable with an explanation so that I can understand it.

+2


source to share


1 answer


You're almost there - you're just missing a type parameter:

public static IOrderedQueryable<T> OrderBy<T, TKey>(
  this IQueryable<T> source, Expression<Func<T, TKey>> func, bool isDescending) {
  return isDescending ? source.OrderByDescending(func) : source.OrderBy(func);
}

      



Your code didn't work before because the type of the parameter was func

used TKey

and it was not one of the type parameters in the method declaration. The above should work fine.

+4


source







All Articles