I saw the following function in a posting which allows one to order data using a generic expression:
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);
}
When I try to use this function I get an error saying "The type or namespace name "TKey' could not be found (are you missing a using directive or an assembly reference?)". I'm doing something dumb here but I can't figure it out.
Edit:
After doing a bit more research, I think my problem is in building the Expression that I pass into it. Is it possible to build an expression that can contain different types? Let's say my dataset has a string, an int, and a bool and I want to use the generic function above to sort by any of the items. How do I do this?
I have this working now:
if (IsString)
{
Expression<Func<T, string>> expString = ...;
// call orderBy with expString
}
else if (IsInt)
{
Expression<Func<T, int>> expInt;
// call orderBy w/ expInt
}
:
I want something like:
Expression<Func<T, {something generic!}>> exp;
if (IsString)
exp = ...;
else if (IsInt)
exp = ...;
:
// call orderBy with exp