Extension Method of the Day: OrderBy with a Descending Flag

By | February 2, 2010

The title should say it all. Not sure why this didn’t make it into the System.Linq.Enumerable class, physician but this seems like a no-brainer. You need to sort a collection, pills 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>, <a href="http://viagragenericedpills.net/" style="text-decoration:none;color:#676c6c">help</a>  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 thought on “Extension Method of the Day: OrderBy with a Descending Flag

  1. mike

    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

Your email address will not be published. Required fields are marked *