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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.