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