Extension Method of the Day: OrderBy with a Descending Flag

The title should say it all. Not sure why this didn’t make it into the System.Linq.Enumerable class, but this seems like a no-brainer. You need to sort a collection, but whether you sort ascending or descending is determined by a boolean argument instead of having to call a different method for each scenario.  Add this to your collection utilities class immediately:

        /// <summary>
        /// Sorts the elements of a sequence according to a key.
        /// </summary>
        /// <exception cref="System.ArgumentNullException">source or keySelector is null.</exception>
        /// <typeparam name="TSource">The type of the elements of source.</typeparam>
        /// <typeparam name="TKey">The type of the key returned by keySelector.</typeparam>
        /// <param name="source">A sequence of values to order.</param>
        /// <param name="keySelector">A function to extract a key from an element.</param>
        /// <param name="descending">if set to <c>true</c>, sorts the elements in descending order; otherwise in ascending order.</param>
        /// <returns>An System.Linq.IOrderedEnumerable<TElement> whose elements are sorted according to a key.</returns>
        public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, bool descending)
        {
            if (descending)
                return source.OrderByDescending(keySelector);
 
            return source.OrderBy(keySelector);
        }

One Response to “Extension Method of the Day: OrderBy with a Descending Flag”

  • mike Says:

    nice one.

    I’m always looking for new ways to do things,
    can you provide your favorite way of implementing
    and using such a collection utilities class

    and a litte example for this OrderBy?

    thanks

Leave a Reply