Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

c# - Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type

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

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

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

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...