且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Linq to Sql - 存储库模式 - 动态 OrderBy

更新时间:2023-02-13 16:30:40

如果您只是在没有完整的 Dynamic-Linq 内容的情况下进行动态排序,您可以查看我不久前写的一篇文章:点击

If you're just after dynamic sorting without the full Dynamic-Linq stuff you can check out a post I wrote about this a while back: click

我真的不再写博客了,所以这里是实际的扩展方法:

I don't really blog anymore so here's the actual extension method:

public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string sortExpression) where TEntity : class
    {
        if (string.IsNullOrEmpty(sortExpression))
            return source; // nothing to sort on

        var entityType = typeof(TEntity);
        string ascSortMethodName = "OrderBy";
        string descSortMethodName = "OrderByDescending";            
        string[] sortExpressionParts = sortExpression.Split(' ');
        string sortProperty = sortExpressionParts[0];
        string sortMethod = ascSortMethodName;

        if (sortExpressionParts.Length > 1 && sortExpressionParts[1] == "DESC")
            sortMethod = descSortMethodName;    

        var property = entityType.GetProperty(sortProperty);
        var parameter = Expression.Parameter(entityType, "p");
        var propertyAccess = Expression.MakeMemberAccess(parameter, property);
        var orderByExp = Expression.Lambda(propertyAccess, parameter);

        MethodCallExpression resultExp = Expression.Call(
                                            typeof(Queryable), 
                                            sortMethod, 
                                            new Type[] { entityType, property.PropertyType },
                                            source.Expression, 
                                            Expression.Quote(orderByExp));

        return source.Provider.CreateQuery<TEntity>(resultExp);
    }