CSharp · Console
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
public class Program
{
public static void Main()
{
string[] companies = {
"Consolidated Messenger", "Alpine Ski House", "Southridge Video", "City Power & Light",
"Coho Winery", "Wide World Importers", "Graphic Design Institute", "Adventure Works",
"Humongous Insurance", "Woodgrove Bank", "Margie's Travel", "Northwind Traders",
"Blue Yonder Airlines", "Trey Research", "The Phone Company",
"Wingtip Toys", "Lucerne Publishing", "Fourth Coffee"
};
var openOrderBy = typeof(Queryable)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.First(m => m.Name == "OrderBy" && m.GetParameters().Length == 2);
var closedOrderBy = openOrderBy.MakeGenericMethod(
typeof(string), // type of item in collection, TSource
typeof(string)); // type returned by lambda, TKey
var pe = Expression.Parameter(typeof(string), "company");
var orderByCall = Expression.Call(null, // for static methods
closedOrderBy,
companies.AsQueryable().Expression,
Expression.Lambda<Func<string, string>>(pe, pe));
var result = Expression.Lambda<Func<IQueryable<string>>>(orderByCall).Compile().Invoke().ToList();
result.ForEach(Console.WriteLine);
}
}