tags:

views:

81

answers:

1

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 such as x => x.DateOfBirth etc. What I would like to do is place that in a generic extension method that I could parse my expression, and a boolean isDescending to, but I'm not sure how to do this. 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? Preferably with an explanation so that I can understand it.

+4  A: 

You're very nearly 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 wasn't working before because the func parameter's type used TKey, and that wasn't one of the type parameters in your method declaration. The above should work fine.

Jon Skeet