Cannot Convert from Method Group to Object - C#

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

I am trying to get familiar with C# and tried out the following program - it just outputs the average of the even numbers in the Array.

Would be great if someone could highlight the problem here.

回答1:

You need select.Average() (with the parens).



回答2:

The Missing Parenthesis () is the reason for your error.It should be Average()

without a Parenthesis,it is understood as a method group.The average method could have multiple overloads and it is unclear which specific overloaded method needs to be invoked.But when you mention the parenthesis it makes the intention clearer and the method gets called.



回答3:

You are not calling Average. should be select.Average()



回答4:

It's an Extension Method so it should be like this: Average()

with ( Parenthesis() )



回答5:

the problem is that, you forgot to include the parenthesis since Average is a method (extension type). Another solution is to use lambda expression, something like this,

var numbers = new[] { 1, 2, 3, 4, 5 }; Console.WriteLine(numbers.Where(x => (x % 2) == 0).Average()); 

or

var numbers = new[] { 1, 2, 3, 4, 5 }; var select = (from num in numbers where (num % 2) == 0 select num).Average(); Console.WriteLine(select); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!