Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 389
Sako73 Avatar asked Jun 01 '26 21:06

Sako73


1 Answers

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) });
like image 106
Pavel Minaev Avatar answered Jun 04 '26 12:06

Pavel Minaev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!