0

I have the following function:

    public List<TopMediansModel> QueryForMedians(string state, string median)
    {
        ApplicationDbContext db = new ApplicationDbContext();
        return (from q in db.StateSuburbLocation
                where (q.State == state)
                orderby q.GetType().GetProperty(median) descending
                select new TopMediansModel
                {
                    Median = median,
                    MedianValue = q.GetType().GetProperty(median),
                    MedianSuburb = q.Suburb
                }).Take(10).ToList();
    }

Is it possible to have the orderby and MedianValue 'properties' as variables?

I've tried using the GetType().GetProperty() Methods, and am no doubt doing so incorrectly.

0

1 Answer 1

2

You can use something like Dynamic Linq

return db.StateSuburbLocation
         .Where(l => l.State == state)
         .OrderByDescending(median)
         .Select(l => new TopMediansModel {
             Median = median,
             MedianValue = q.GetType().GetProperty(median),
             MedianSuburb = q.Suburb
          }).Take(10).ToList();

Or you can build query expression manually

    public static IQueryable<T> OrderByDescending<T>(
        this IQueryable<T> source, string propertyName)
    {         
        var parameter = Expression.Parameter(typeof(T), "p");
        var property = Expression.PropertyOrField(parameter, propertyName);
        var keySelector = Expression.Lambda<Func<T, object>>(property, parameter);
        return source.OrderByDescending(keySelector);
    }

Usage is same

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

2 Comments

Thanks for the feedback Sergey, I'd prefer not to use another reference as I'll only be doing this in one function. Could you explain what you mean by building the query expression manually?
Trying this I get the following error Error 1 The type arguments for method 'System.Linq.Enumerable.OrderByDescending<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TKey>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

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.