fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5.  
  6. class Foo
  7. {
  8. public Foo(string value) { Value = value; }
  9. public string Value { get; private set; }
  10. }
  11.  
  12. public class Test
  13. {
  14. public static void Main()
  15. {
  16. IEnumerable<Foo> collection = new[] { new Foo("zyx"), new Foo("abc") };
  17. IEnumerable<Foo> ordered = OrderBy(collection, "Value");
  18. ordered.Select(f => f.Value).ToList().ForEach(Console.WriteLine);
  19. }
  20.  
  21. public static IEnumerable<T> OrderBy<T>(IEnumerable<T> collection,
  22. string columnName)
  23. {
  24. ParameterExpression param = Expression.Parameter(typeof(T), "x"); // x
  25. Expression property = Expression.Property(param, columnName); // x.ColumnName
  26. Func<T, object> lambda = Expression.Lambda<Func<T, object>>( // x => x.ColumnName
  27. Expression.Convert(property, typeof(object)),
  28. param)
  29. .Compile();
  30.  
  31. Func<IEnumerable<T>, Func<T, object>, IEnumerable<T>> expression = (c, f) => c.OrderBy(f);
  32.  
  33. IEnumerable<T> sorted = expression(collection, lambda);
  34. return sorted;
  35. }
  36. }
Success #stdin #stdout 0.1s 35464KB
stdin
Standard input is empty
stdout
abc
zyx