以下问题:OrderBy extension method for NPoco.Linq
,因此是这个问题:Natural sort with Dynamic Linq including multiple sorting parameters
带有比较器的OrderBy对NPOCO的外观如何? 我一直试图匹配自己创建的答案,但没有设法将带有比较器的Expression.Call转换为Invoke。到目前为止,我都没有尝试过这个:
public static IQueryProvider<T> OrderByField<T, ComparerType>(this IQueryProvider<T> queryProvider, IComparer<ComparerType> comparer, string SortField, bool ascending)
{
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, SortField);
string methodName = ascending ? "OrderBy" : "OrderByDescending";
Expression conversion = Expression.Convert(prop, typeof(object));
LambdaExpression lambda = Expression.Lambda(conversion, param);
try
{
object result = typeof(IQueryProvider<T>).GetMethods().Single(
method => method.Name == methodName)
.Invoke(queryProvider, new object[] { comparer, lambda });
return (IQueryProvider<T>)result;
}
catch(Exception exc)
{
return null;
}
}