-
-
Save gnncl/18224c72078df3cb2e05967bdde60cb1 to your computer and use it in GitHub Desktop.
Sorting expression dynamically using LINQ
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.Linq.Expressions; | |
public static class EnumerableExtensions | |
{ | |
public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> collection, | |
string columnName, SortDirection direction = SortDirection.Ascending) | |
{ | |
ParameterExpression param = Expression.Parameter(typeof(T), "x"); // x | |
Expression property = Expression.Property(param, columnName); // x.ColumnName | |
Func<T, object> lambda = Expression.Lambda<Func<T, object>>( // x => x.ColumnName | |
Expression.Convert(property, typeof(object)), | |
param) | |
.Compile(); | |
Func<IEnumerable<T>, Func<T, object>, IEnumerable<T>> expression = | |
SortExpressionBuilder<T>.CreateExpression(direction); | |
IEnumerable<T> sorted = expression(collection, lambda); | |
return sorted; | |
} | |
} |
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
public enum SortDirection | |
{ | |
Ascending, | |
Descending | |
} |
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
public static class SortExpressionBuilder<T> | |
{ | |
private static IDictionary<SortDirection, ISortExpression> directions = | |
new Dictionary<SortDirection, ISortExpression> | |
{ | |
{ SortDirection.Ascending, new OrderByAscendingSortExpression() }, | |
{ SortDirection.Descending, new OrderByDescendingSortExpression() } | |
}; | |
interface ISortExpression | |
{ | |
Func<IEnumerable<T>, Func<T, object>, IEnumerable<T>> GetExpression(); | |
} | |
class OrderByAscendingSortExpression : ISortExpression | |
{ | |
public Func<IEnumerable<T>, Func<T, object>, IEnumerable<T>> GetExpression() | |
{ | |
return (c, f) => c.OrderBy(f); | |
} | |
} | |
class OrderByDescendingSortExpression : ISortExpression | |
{ | |
public Func<IEnumerable<T>, Func<T, object>, IEnumerable<T>> GetExpression() | |
{ | |
return (c, f) => c.OrderByDescending(f); | |
} | |
} | |
public static Func<IEnumerable<T>, Func<T, object>, | |
IEnumerable<T>> CreateExpression(SortDirection direction) | |
{ | |
return directions[direction].GetExpression(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment