如果不首先将 lambda 表达式强制转换为委托或表达式树类型,则不能将该表达式用作动态分派操作的参数

我使用的是.NET4.5和 VS2013,我有一个从 db 获得 dynamic结果的查询。

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

以下语句失败,编译错误为 Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type 都不让我管理

topAgents.ToList().Select(agent => new
{
User = agent.User != null ? string.Format("{0}", agent.User).Replace("CORPNTGB\\", "") : null,
Amount = agent.Amount
});

而这个带 foreach的工作正常。

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<List<object>>();第二条语句是编译器允许的吗?

为什么编译器不允许 LINQ 选择,而允许每个‘ ?

78947 次浏览

The problem is that topAgents is dynamic - so your ToList() call is dynamic, and so is Select. That has issues that:

  1. you can't use lambda expressions for dynamic calls like this;
  2. dynamic calls don't find extension methods anyway.

Fortunately, the operations don't need to be dynamic just because the element type is dynamic. You could use:

IEnumerable<dynamic> topAgents = ...;

... or just use var. Both of those should be fine.