Cannot Convert from Method Group to Object - C#

前端 未结 6 1881
野趣味
野趣味 2021-01-12 03:23

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.

6条回答
  •  囚心锁ツ
    2021-01-12 04:02

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

提交回复
热议问题