Multiple “order by” in LINQ

后端 未结 7 1626
小蘑菇
小蘑菇 2020-11-22 00:16

I have two tables, movies and categories, and I get an ordered list by categoryID first and then by Name.

7条回答
  •  不知归路
    2020-11-22 00:37

    I have created some extension methods (below) so you don't have to worry if an IQueryable is already ordered or not. If you want to order by multiple properties just do it as follows:

    // We do not have to care if the queryable is already sorted or not. 
    // The order of the Smart* calls defines the order priority
    queryable.SmartOrderBy(i => i.Property1).SmartOrderByDescending(i => i.Property2);
    

    This is especially helpful if you create the ordering dynamically, f.e. from a list of properties to sort.

    public static class IQueryableExtension
    {
        public static bool IsOrdered(this IQueryable queryable) {
            if(queryable == null) {
                throw new ArgumentNullException("queryable");
            }
    
            return queryable.Expression.Type == typeof(IOrderedQueryable);
        }
    
        public static IQueryable SmartOrderBy(this IQueryable queryable, Expression> keySelector) {
            if(queryable.IsOrdered()) {
                var orderedQuery = queryable as IOrderedQueryable;
                return orderedQuery.ThenBy(keySelector);
            } else {
                return queryable.OrderBy(keySelector);
            }
        }
    
        public static IQueryable SmartOrderByDescending(this IQueryable queryable, Expression> keySelector) {
            if(queryable.IsOrdered()) {
                var orderedQuery = queryable as IOrderedQueryable;
                return orderedQuery.ThenByDescending(keySelector);
            } else {
                return queryable.OrderByDescending(keySelector);
            }
        }
    }
    

提交回复
热议问题