如果没有首先将 lambda 表达式转换为委托或表达式树类型,则不能将 lambda 表达式用作动态调度操作的参数 [英] Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type
问题描述
我正在使用 .NET4.5 和 VS2013,我有一个从数据库获取 dynamic
结果的查询.
I am working with .NET4.5 and VS2013, I have this query that gets dynamic
result from db.
dynamic topAgents = this._dataContext.Sql(
"select t.create_user_id as "User", sum(t.netamount) as "Amount" from transactiondetail t where t.update_date > sysdate -7 group by t.create_user_id")
.QueryMany<dynamic>();
以下语句因编译错误而失败 不能使用 lambda 表达式作为动态调度操作的参数,而无需先将其转换为委托或表达式树类型
甚至不允许我运行它
Following statement fails with compilation error Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type
without even allowing me to run it
topAgents.ToList().Select(agent => new
{
User = agent.User != null ? string.Format("{0}", agent.User).Replace("CORPNTGB\", "") : null,
Amount = agent.Amount
});
虽然这个带有 foreach
的效果很好.
while this one with foreach
works just fine.
var data = new List<List<object>>();
foreach (dynamic agent in topAgents)
{
data.Add(new List<object>
{
agent.User != null ? string.Format("{0}", agent.User).Replace("CORPNTGB\", "") : null,
agent.Amount
});
}
在我 topAgents.ToList()
之后的我眼中,它们可以被解释为等效的,是不是因为我明确声明 var data = new List
编译器允许第二条语句吗?>();
In my eyes after I topAgents.ToList()
they could be interpreted as equivalent, is it because I explicitly state that var data = new List<List<object>>();
that second statement is allowed by compiler?
为什么编译器不允许 LINQ select,但允许每个`?
推荐答案
问题在于 topAgents
是 dynamic
- 所以你的 ToList()
调用是动态的,Select
也是如此.这有以下问题:
The problem is that topAgents
is dynamic
- so your ToList()
call is dynamic, and so is Select
. That has issues that:
- 不能将 lambda 表达式用于这样的动态调用;
- 动态调用无论如何都找不到扩展方法.
幸运的是,操作不需要是动态的,只是因为 element 类型是动态的.你可以使用:
Fortunately, the operations don't need to be dynamic just because the element type is dynamic. You could use:
IEnumerable<dynamic> topAgents = ...;
... 或者只使用 var
.这两个都应该没问题.
... or just use var
. Both of those should be fine.
这篇关于如果没有首先将 lambda 表达式转换为委托或表达式树类型,则不能将 lambda 表达式用作动态调度操作的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!