Last active
January 2, 2016 00:09
-
-
Save davidwhitney/8221186 to your computer and use it in GitHub Desktop.
Expression sorting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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