using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.UI.WebControls;
public static void Main()
IEnumerable<Order> orders = new[]
CustomerInfo = new Customer
CustomerInfo = new Customer
orders = orders.OrderBy<Order>("FirstName", SortDirection.Ascending);
public Int32 OrderID{ get; set; }
public String OrderNumber { get; set; }
public Customer CustomerInfo { get; set;}
public Int64 CustomerNumber { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String Phone { get; set; }
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();
public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> collection,
string columnName, SortDirection direction)
ParameterExpression param = Expression.Parameter(typeof(T), "x");
Expression property = Expression.Property(param, columnName);
Func<T, object> lambda = Expression.Lambda<Func<T, object>>(
Expression.Convert(property, typeof(object)),
Func<IEnumerable<T>, Func<T, object>, IEnumerable<T>> expression = SortExpressionBuilder<T>.CreateExpression(direction);
IEnumerable<T> sorted = expression(collection, lambda);