using System.Collections.Generic;
using System.Diagnostics;
using System.Linq.Expressions;
public double Price { get; set; }
public string Brand { get; set; }
public static IQueryable<Phone> Phones
new Phone(){ Price = 2, Brand = "A"},
new Phone(){ Price = 1, Brand = "B"}
public static class Utility
public static Expression<Func<TSource, object>> GetExpression<TSource>(string propertyName)
var param = Expression.Parameter(typeof(TSource), "x");
Expression conversion = Expression.Convert(Expression.Property(param, propertyName), typeof(object));
return Expression.Lambda<Func<TSource, object>>(conversion, param);
public static Func<TSource, object> GetFunc<TSource>(string propertyName)
return GetExpression<TSource>(propertyName).Compile();
public static IOrderedEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> source, string propertyName)
return source.OrderBy(GetFunc<TSource>(propertyName));
public static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string propertyName)
return source.OrderBy(GetExpression<TSource>(propertyName));
public static void Dump(IEnumerable<Phone> phones, string mesg)
Console.WriteLine("\n" + mesg);
foreach (var item in phones)
Console.WriteLine(String.Format("Brand = {0}, Price = {1}", item.Brand, item.Price));
public static void Main(string[] args)
List<Phone> orderedByPrice = null;
List<Phone> orderedByBrand = null;
orderedByPrice = Db.Phones.OrderBy(x => x.Price).ToList();
orderedByBrand = Db.Phones.OrderBy(x => x.Brand).ToList();
Dump(orderedByPrice, "lambda expression, Order By: Price");
Dump(orderedByBrand, "lambda expression, Order By: Brand");
orderedByPrice = Db.Phones.OrderBy("Price").ToList();
orderedByBrand = Db.Phones.OrderBy("Brand").ToList();
Dump(orderedByPrice, "Source is IQueryable, Order By: Price");
Dump(orderedByBrand, "source is IQueryable, Order By: Brand");
orderedByPrice = Db.Phones.AsEnumerable().OrderBy("Price").ToList();
orderedByBrand = Db.Phones.AsEnumerable().OrderBy("Brand").ToList();
Dump(orderedByPrice, "Source is IEnumerable, Order By: Price");
Dump(orderedByBrand, "Source is IEnumerable, Order By: Brand");