trentacular » c# http://trentacular.com Trent Foley's Spectacular Technical Blog Wed, 10 Aug 2011 23:13:09 +0000 en hourly 1 http://wordpress.org/?v=3.3.2 Extension Method of the Day: OrderBy with a Descending Flag http://trentacular.com/2010/02/extension-method-of-the-day-orderby-with-a-descending-flag/ http://trentacular.com/2010/02/extension-method-of-the-day-orderby-with-a-descending-flag/#comments Tue, 02 Feb 2010 23:52:16 +0000 Trent http://trentacular.com/?p=241 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);
        }
]]>
http://trentacular.com/2010/02/extension-method-of-the-day-orderby-with-a-descending-flag/feed/ 1