0

So I have a controller that accepts a string "sortBy"

My Controller:

 public async Task<ViewResult> ActivityManagementTwo(DateFilterModel filters, int pageSize = 25, int page = 1, string sortBy = "")      
    {
        // do stuff 

            Activities = activities.OrderBy(a=> a.GetType().GetProperty(sortBy)).Skip((page-1)*pageSize).Take(pageSize),

        // do more stuff
    }

I want to basically say

 if(sortBy == "dateTimeOfCall") activities.orderBy(a=> a.dateTimeOfCall);
 else if (sortyBy == "trackingNumber") activities.orderBy(a=>a.trackingNumber);
 // so on and so forth-

but I don't want to make a seperate if statement for each property in activities. Is there a short way to orderby a property that matches a string?

Neovssmith
  • 83
  • 7

2 Answers2

1

You can use reflection to get the property name.

activites= activities.OrderBy(a => a.GetType().GetProperty(sortBy).GetValue(a, null)).Skip((page-1)*pageSize).Take(pageSize);

See some more options and discussion on this question.

Aliza Berger
  • 171
  • 3
  • 6
0

For the situations like this you should use Expression in c# you can use an extension method as follows:

public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering, bool descending)
{
    var type = typeof(T);
    var property = type.GetProperty(ordering);
    var parameter = Expression.Parameter(type, "p");
    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
    var orderByExp = Expression.Lambda(propertyAccess, parameter);
    MethodCallExpression resultExp = 
        Expression.Call(typeof(Queryable), (descending ? "OrderByDescending" : "OrderBy"), 
            new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExp));
    return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(resultExp);
}
Abolfazl
  • 1,591
  • 8
  • 21