获得内部对象的属性

时间:2015-12-22 12:39:35

标签: c# tree expression

您好我正在尝试使用该代码获取包含User的客户的属性User.Email。但它是一个对象(User类型的用户)所以它抛出异常。我应该修理什么?

public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
    {
        if (!string.IsNullOrWhiteSpace(SortField))
        {
            var param = Expression.Parameter(typeof (T), "p");
            var prop = Expression.Property(param, SortField);
            var exp = Expression.Lambda(prop, param);
            string method = Ascending ? "OrderBy" : "OrderByDescending";
            Type[] types = new Type[] {q.ElementType, exp.Body.Type};
            var mce = Expression.Call(typeof (Queryable), method, types, q.Expression, exp);
            return q.Provider.CreateQuery<T>(mce);
        }
        else
        {
            return q;
        }
    }

1 个答案:

答案 0 :(得分:0)

您需要将属性路径传递给该函数(例如&#34; User.Email&#34;)并在内部进行说明,如下所示

public static IQueryable<T> OrderByField<T>(this IQueryable<T> source, string sortField, bool ascending)
{
    if (string.IsNullOrWhiteSpace(sortField)) return source;
    var item = Expression.Parameter(typeof(T), "item");
    Expression member = null;
    foreach (var memberName in sortField.Split('.'))
        member = Expression.PropertyOrField(member ?? item, memberName);
    var selector = Expression.Lambda(member, item);
    var method = ascending ? "OrderBy" : "OrderByDescending";
    var types = new [] { source.ElementType, selector.Body.Type };
    var expression = Expression.Call(typeof(Queryable), method, types, source.Expression, selector);
    return source.Provider.CreateQuery<T>(expression);
}

必不可少的部分是

    var item = Expression.Parameter(typeof(T), "item");
    Expression member = null;
    foreach (var memberName in sortField.Split('.'))
        member = Expression.PropertyOrField(member ?? item, memberName);

从expression参数开始,为路径中指定的每个成员构建一个访问器。