Select语句中的变量

时间:2015-05-11 04:34:17

标签: c# linq

我有以下功能:

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

是否可以将orderbyMedianValue'属性'作为变量?

我尝试过使用GetType().GetProperty()方法,毫无疑问这样做不正确。

1 个答案:

答案 0 :(得分:2)

您可以使用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();

或者您可以手动构建查询表达式

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

用法相同