LINQ orderby 排序妙用

做排序,项目中发现好多地方要用到排序,什么正序、倒序、写的很累,不过为发现排序写一个综合方法很不错的

1、得到某某的数据

  IEnumerable<xxxx> = .....................;

2、得到要排序的参数orderby

  orderby参数格式:

  orderby = "CreateTime asc,Title desc";

--------------------------------------------------------------------------

  OrderUsingSortExpression(res.AsQueryable(), orderby).AsEnumerable();

3、对数据进行排序的方法

     public static IOrderedQueryable<TEntity> OrderUsingSortExpression<TEntity>(this IQueryable<TEntity> source, string sortExpression) where TEntity : class
        {
            String[] orderFields = sortExpression.Split(',');
            IOrderedQueryable<TEntity> result = null;
            for (int currentFieldIndex = 0; currentFieldIndex < orderFields.Length; currentFieldIndex++)
            {
                String[] expressionPart = orderFields[currentFieldIndex].Trim().Split(' ');
                String sortField = expressionPart[0];
                Boolean sortDescending = (expressionPart.Length == 2) && (expressionPart[1].Equals("DESC", StringComparison.OrdinalIgnoreCase));
                if (sortDescending)
                {
                    result = currentFieldIndex == 0 ? source.OrderByDescending(sortField) : result.ThenByDescending(sortField);
                }
                else
                {
                    result = currentFieldIndex == 0 ? source.OrderBy(sortField) : result.ThenBy(sortField);
                }
            }
            return result;
        }

  4、这样所有的后台方法不论排序有多少个,只用定义一个orderby参数,按照一定的规格就好了

posted on 2011-07-25 18:00  水星曙光  阅读(5490)  评论(1编辑  收藏  举报