2009-12-11 114 views
3

(对不起,我想很好地格式化,但我不能让代码格式化才能正常工作)构建一个LINQ表达式

我得到:

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

我认为我需要在可查询的对象本身来传递,但我无法弄清楚如何做到这一点(如果它甚至需要)。

任何帮助表示赞赏。

谢谢。

+0

感谢您的格式帮助。 – Sako73 2009-12-11 19:12:41

回答

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

不错。另外,您可以通过用“单一”调用替换“Where”调用并用typeof(字符串)替换新的Type [] {typeof(string)}来简化语句,但这只是勉强。 – 2009-12-11 19:05:11

+0

谢谢,我正在寻找什么。 – Sako73 2009-12-11 19:14:23