泛型怎么样:
辅助方法:
public static Expression<Func<TEntity, TResult>> GetExpression<TEntity, TResult>(string prop)
{
var param = Expression.Parameter(typeof(TEntity), "p");
var parts = prop.Split('.');
Expression parent = parts.Aggregate<string, Expression>(param, Expression.Property);
Expression conversion = Expression.Convert(parent, typeof (object));
var tryExpression = Expression.TryCatch(Expression.Block(typeof(object), conversion),
Expression.Catch(typeof(object), Expression.Constant(null)));
return Expression.Lambda<Func<TEntity, TResult>>(tryExpression, param);
}
样本层次结构:
public class A
{
public A(B b)
{
B = b;
}
public B B { get; set; }
}
public class B
{
public B(C c)
{
C = c;
}
public C C { get; set; }
}
public class C
{
public C(int id)
{
this.Id = id;
}
public int Id { get; set; }
}
例子:
var list = new List<B>
{
new B(new A(new C(1))),
new B(new A(new C(2))),
new B(new A(new C(3))),
new B(new A(null)),
new B(null)
}.AsQueryable();
var ordered = list.OrderByDescending(GetExpression<B, Object>("AProp.CProp.Id"));
输出:
3
2
1
Null
Null