Reputation: 1951
I'm trying to figure out how to sort by a variable, not a string.
I believe I should be able to represent x => x.SomeProperty
and save that to a variable and pass it into the OrderBy
method but can't figure out what to use here.
SomeType sortExpr = null;
switch(sortByColumnName)
{
case "Name":
sortExpr = x => x.Name
break;
case "Age":
sortExpr = x => x.Age
break;
case "OtherThing":
sortExpr = x => x.OtherReference.Name
break;
}
if (sortDirection == "asc")
query = query.OrderBy(sortExpr);
else
query = query.OrderByDescending(sortExpr);
Upvotes: 1
Views: 1476
Reputation: 37500
As already said, OrderBy
accepts Func<TSource,TKey> keySelector
as its argument so sortExpr
should e of that type, where TSource
is object, which is stored in collection you want to sort, let's say of User
class. TKey
is type of property you want to sort by, since this can be of arbitrary type, you can make it object
, as this type parameter is covariant.
So declare like
Func<User, object> sortExpr;
and rest code can stay as it is.
EDIT
If you are using IQueryable<TSource>.OrderBy
version, which requires Expression<Func<TSource, TKey>>
, then you just need to delare the variable as:
Expression<Func<User, object>> sortExpr;
Upvotes: 4