Reputation: 311
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.
Upvotes: 0
Views: 73
Reputation: 236328
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
Upvotes: 2