从泛型方法构造Linq表达式

时间:2009-12-11 18:41:02

标签: linq expression-trees

(抱歉,我尝试将其格式化,但我无法使代码格式化正常工作)

我明白了:

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

执行时:

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

我认为我需要传递可查询对象本身,但我无法弄清楚如何执行此操作(如果它甚至是必需的)。

感谢任何帮助。

感谢。

1 个答案:

答案 0 :(得分:3)

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