数组平均方法错误

时间:2017-02-15 16:55:40

标签: c#

我收到错误

  

错误CS1929' uint []'不包含'平均值'的定义和   最好的扩展方法是重载   ' Queryable.Average(IQueryable的)'需要一个类型的接收器   ' IQueryable的' ArrayLengthTest D:\ Visual   Studio \ ArrayLengthTest \ ArrayLengthTest \ Program.cs 17活动

uint[] asd = new uint[5];
            for (uint i = 0; i < asd.Length; i++)
            {
                asd[i] = i;
            }
            uint arrayAverage = asd.Average();

任何想法是什么意思?我知道我可以很容易地使用整数但我要求提示......

1 个答案:

答案 0 :(得分:0)

您可以使用

using System.Linq;

或查看此帖子how-can-i-return-the-sum-average-of-an-int-array

UPDATE [使用refl]您可以尝试实现自定义Avarage扩展 [这是一个简单的想法]

public static uint Average(this IEnumerable<uint> source)
    {
        if (source == null) throw new Exception(); 
        long sum = 0;
        long count = 0;
        checked
        {
            foreach (uint v in source)
            {
                sum += v;
                count++;
            }
        }
        if (count > 0) return(uint)((double)sum / count);
        throw new Exception();
    }