前言
在Dotnet开发过程中,Average作为IEnumerable的扩展方法,十分常用。本文对Average方法的关键源码进行简要分析,以方便大家日后更好的使用该方法。.
使用
Average 计算数值序列的平均值
假如我们有这样的一个集合
 List<int> grades = new List<int> { 78, 92, 100, 37, 81 };
- 
	
不使用linq  
我们要计算该集合的平均值,且不能使用linq,那么我们的计算平均值方法和下面这段代码应该没有多大的出入
 double Average(List<int> source)
 {
            if (source == null)
            {
                throw new Exception("集合不能为空");
            }
            long sum = 0L;
            long count = 0L;
            foreach (var item in source)
            {
                sum += item;
                count++;
            }
            if (count == 0)
            {
                throw new Exception("无元素");
            }
            return (double)sum / (double)count;
}
- 
	
使用linq  
double average = grades.Average();
源码解析
方法
public static double Average(this IEnumerable<int> source)
参数
- 
	
source 元素的类型  
返回值
- 
	
double  
源码:
 public static double Average(this IEnumerable<int> source)
        {
            if (source == null)
            {
                throw new Exception("source is null");
            }
            long num = 0L;
            long num2 = 0L;
            checked
            {
                foreach (int item in source)
                {
                    num += item;
                    num2++;
                }
                if (num2 > 0)
                {
                    return (double)num / (double)num2;
                }
                throw new Exception("NoElements");
            }
        }
将上述代码放到cheked块里面,就会使运行时引发System.OverflowException异常。这样就可以让你的运算更加准确,避免二进制的回绕。
Enumerable.Average() 重载方法一共十多个,这里选择了最典型的一个讲解!
总结
文章来源于即兴发挥,本篇就说到这里啦,希望对您有帮助。