linq-Average

        public static float? Average(this IEnumerable<float?> source) {
            if (source == null) throw Error.ArgumentNull("source");
            double sum = 0;
            long count = 0;
            checked {
                foreach (float? v in source) {
                    if (v != null) {
                        sum += v.GetValueOrDefault();
                        count++;
                    }
                }
            }
            if (count > 0) return (float)(sum / count);
            return null;
        }

求平均数。

List<int> grades = new List<int> { 78, 92, 100, 37, 81 };

double average = grades.Average();

 

posted @ 2021-11-15 14:57  vba是最好的语言  阅读(26)  评论(0编辑  收藏  举报