在未先将其转换为委托或表达式树类型的情况下,无法将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

查看:993
本文介绍了在未先将其转换为委托或表达式树类型的情况下,无法将lambda表达式用作动态调度的操作的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用.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>();

以下语句失败,并出现编译错误Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type 甚至不允许我运行它

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

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选择,但允许每个`?

推荐答案

问题是topAgentsdynamic-因此您的ToList()调用是动态的,而Select也是动态的.那有个问题:

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

  1. 您不能将lambda表达式用于这样的动态调用;
  2. 动态调用始终找不到扩展方法.

幸运的是,仅由于 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表达式用作动态调度的操作的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆