如何使用表达式实现特定的OrderBy?

时间:2014-05-15 19:51:48

标签: c# linq linq-expressions

尝试实现自定义linq查询以按任何字段对数据集进行排序(首先获取行,哪个字段等于搜索字符串,然后获取所有其他字段)。 最终查询应该是这样的:

    source.OrderBy(p => p.Phone == "1234567")

代码:

    var type = typeof(T);
    var property = type.GetProperty(sortPropertyOrder.FieldName.ToString());
    var parameter = Expression.Parameter(type, "p");
    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
    string methodName = sortPropertyOrder.SortDirection == ListSortDirection.Ascending ? "OrderBy" : "OrderByDescending";
    Type[] typeArguments = new Type[] { type, property.PropertyType };
    object fieldValue = Convert(property.PropertyType, sortPropertyOrder.FieldValue);

    Expression equalExp = Expression.Equal(propertyAccess, Expression.Constant(fieldValue));
    Expression finalExpression = Expression.Quote(Expression.Lambda(equalExp, parameter));
    MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName, typeArguments, source.Expression, finalExpression);
    IQueryable<T> query = source.Provider.CreateQuery<T>(resultExp);

因此,我有一个例外:没有通用方法&#39; OrderBy&#39; on type&#39; System.Linq.Queryable&#39;与提供的类型参数和参数兼容。如果方法是非泛型的,则不应提供类型参数。

虽然我创建了更简单的查询(source.OrderBy(p =&gt; p.Phone))

    var type = typeof(T);
    var property = type.GetProperty(sortPropertyOrder.FieldName.ToString());
    var parameter = Expression.Parameter(type, "p");
    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
    string methodName = sortPropertyOrder.SortDirection == ListSortDirection.Ascending ? "OrderBy" : "OrderByDescending";
    Type[] typeArguments = new Type[] { type, property.PropertyType };
    object fieldValue = Convert(property.PropertyType, sortPropertyOrder.FieldValue);
Expression finalExpression = Expression.Quote(Expression.Lambda(propertyAccess, parameter));
MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName, typeArguments, source.Expression, finalExpression);
    IQueryable<T> query = source.Provider.CreateQuery<T>(resultExp);

工作正常。 第一次查询有什么问题?

0 个答案:

没有答案