Search code examples
linqexpression-trees

Construct a Linq Expression from a generic method


(sorry, I tried to format it well, but I cannot get the code formatting to work correctly)

I get:

Incorrect number of arguments supplied for call to method
'System.Linq.IQueryable`1[System.String]
Take[String](System.Linq.IQueryable`1[System.String], Int32)'

when I execute:

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" };

// The IQueryable data to query.
IQueryable<String> queryableData = companies.AsQueryable<string>();

// EXCEPTION HERE
Expression e2 = Expression.Call(
    typeof(Queryable).GetMethods().Where(m => m.Name == "Take")
        .Single().MakeGenericMethod(new Type[] { typeof(string) }),
    new Expression[] { Expression.Constant(4) });

IQueryable<string> res = queryableData.Provider.CreateQuery<string>(e2);

foreach (string s in res)
{
    Console.WriteLine(s);
}

I think that I need to pass in the queryable object itself, but I cannot figure out how to do this (if it is even required).

Any help is appreciated.

Thanks.


Solution

  • Expression e2 = Expression.Call(
        typeof(Queryable).GetMethods().Where(m => m.Name == "Take")
            .Single().MakeGenericMethod(new Type[] { typeof(string) }),
        new Expression[] {
            Expression.Constant(queryableData),
            Expression.Constant(4) });