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

时间:2021-11-18 20:06:56

I am working with .NET4.5 and VS2013, I have this query that gets dynamic result from db.

我正在使用.NET4.5和VS2013,我有这个查询从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>();

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

以下语句因编译错误而失败无法使用lambda表达式作为动态调度操作的参数,而无需先将其转换为委托或表达式树类型,甚至不允许我运行它

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

while this one with foreach works just fine.

虽然这个与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
    });
}

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?

在我的topAntnts.ToList()之后,他们可以被解释为等价,是因为我明确声明var data = new List >();编译器允许第二个语句?

Why doesn't compiler allow LINQ select, but allows for each`?

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

1 个解决方案

#1


68  

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

问题是topAgents是动态的 - 所以你的ToList()调用是动态的,Select也是如此。这有以下问题:

  1. you can't use lambda expressions for dynamic calls like this;
  2. 你不能将lambda表达式用于这样的动态调用;
  3. dynamic calls don't find extension methods anyway.
  4. 动态调用无论如何都找不到扩展方法。

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.

......或者只是使用var。这两个都应该没问题。

#1


68  

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

问题是topAgents是动态的 - 所以你的ToList()调用是动态的,Select也是如此。这有以下问题:

  1. you can't use lambda expressions for dynamic calls like this;
  2. 你不能将lambda表达式用于这样的动态调用;
  3. dynamic calls don't find extension methods anyway.
  4. 动态调用无论如何都找不到扩展方法。

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.

......或者只是使用var。这两个都应该没问题。