问题
I'm trying to perform the following
int myObject = getValues(someVar).Sum(x => Int32.Parse(x.Price))
The function looks this:
List<dynamic> getValues(string something) {...}
This is the error I'm receiving: "Cannot use a lambda expression as an argument to a dynamically dispatched operation"
How can I SUM the values of a List object in a chained call similar to LINQ SUM?
回答1:
Your code works. The problem you are having isn't in the code you posted. This code runs.
void Main() {
int myObject = getValues("12").Sum(x => Int32.Parse(x.Price));
Console.WriteLine (myObject);
}
List<dynamic> getValues(string something) {
var item = new { Price = something };
IEnumerable<dynamic> items = Enumerable.Repeat<dynamic>(item, 2);
return items.ToList();
}
This produces the output 24. The problem may be related to type inference, but that's just a guess. You should include enough code to reproduce the error for a more reliable answer.
回答2:
As mentioned in the comment, this code is working fine for me:-
public static void Main()
{
var result = GetData("test").Sum(x => int.Parse(x.Name));
Console.WriteLine(result);
}
public static List<dynamic> GetData(string x)
{
List<dynamic> data = new List<dynamic>
{
new { Id =1, Name ="1"},
new { Id =2, Name ="4"},
new { Id =3, Name ="5"}
};
return data;
}
I am getting 10 as output.
回答3:
so it ultimately turned out the issue was that I was passing a dynamic variable into the function call and subsequently using LINQ/lambda. Seems like that's a compiler no-no...
dynamic someVar = new {a=1,b=2};
int myObject = getValues(someVar.a).Sum(x => Int32.Parse(x.Price))
回答4:
Your getValues method is returning a dynamic, not a List<dynamic>. Either change your method signature or construct a new List<dynamic>(...) from its results.
dynamic list = new [] {new{Price = "1"},new{Price = "2"}};
// This produces the error you're describing:
Console.WriteLine(list.Sum(x => Int32.Parse(x.Price)));
// This works.
Console.WriteLine(new List<dynamic>(list).Sum(x => Int32.Parse(x.Price)));
来源:https://stackoverflow.com/questions/29754042/cannot-use-a-lambda-expression-as-an-argument-to-a-dynamically-dispatched-operat