Skip to content

Instantly share code, notes, and snippets.

@davidwhitney
Last active January 2, 2016 00:09
Show Gist options
  • Save davidwhitney/8221186 to your computer and use it in GitHub Desktop.
Save davidwhitney/8221186 to your computer and use it in GitHub Desktop.
Expression sorting
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
namespace ExpressionSorting
{
/// <summary>
/// This is a little too clever, it looks like voodoo, but it makes the higher level API totally beautiful.
/// </summary>
public static class ExpressionSortingExtensions
{
/// <summary>
/// Sort by a property expression, with usage like someCollection.OrderByExpression(x=>x.SomeProp);
/// </summary>
public static IEnumerable<TTypeBeingSorted> OrderByExpression<TTypeBeingSorted>(this IEnumerable<TTypeBeingSorted> src, Expression<Func<TTypeBeingSorted, object>> selectorThatPicksThePropertyToSortBy, ListSortDirection direction = ListSortDirection.Ascending)
{
if (selectorThatPicksThePropertyToSortBy == null)
{
return src;
}
var selectedProperty = selectorThatPicksThePropertyToSortBy.Compile();
Func<IEnumerable<TTypeBeingSorted>, IEnumerable<TTypeBeingSorted>> orderingFunction = r => r.OrderBy(selectedProperty);
if (direction == ListSortDirection.Descending)
{
orderingFunction = r => r.OrderByDescending(selectedProperty);
}
return orderingFunction(src);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment