diff --git a/src/libraries/System.Linq/src/System/Linq/Average.cs b/src/libraries/System.Linq/src/System/Linq/Average.cs index 888a43c38ee214..6a36952bfc1aa6 100644 --- a/src/libraries/System.Linq/src/System/Linq/Average.cs +++ b/src/libraries/System.Linq/src/System/Linq/Average.cs @@ -191,6 +191,38 @@ private static TResult Average(this I ThrowHelper.ThrowArgumentNullException(ExceptionArgument.selector); } + // The two loops are separate methods so that each is optimized based on its own use, + // rather than one of them being treated as cold if the other is all that's been seen. + return source.TryGetSpan(out ReadOnlySpan span) ? + Average(span, selector) : + AverageEnumerable(source, selector); + } + + private static TResult Average(ReadOnlySpan span, Func selector) + where TSelector : struct, INumber + where TAccumulator : struct, INumber + where TResult : struct, INumber + { + if (span.IsEmpty) + { + ThrowHelper.ThrowNoElementsException(); + } + + // As in the enumerator-based loop, the sum starts from the first value rather than from zero. + TAccumulator sum = TAccumulator.CreateChecked(selector(span[0])); + for (int i = 1; i < span.Length; i++) + { + checked { sum += TAccumulator.CreateChecked(selector(span[i])); } + } + + return TResult.CreateChecked(sum) / TResult.CreateChecked(span.Length); + } + + private static TResult AverageEnumerable(IEnumerable source, Func selector) + where TSelector : struct, INumber + where TAccumulator : struct, INumber + where TResult : struct, INumber + { using IEnumerator e = source.GetEnumerator(); if (!e.MoveNext()) { @@ -235,6 +267,52 @@ private static TResult Average(this I ThrowHelper.ThrowArgumentNullException(ExceptionArgument.selector); } + return source.TryGetSpan(out ReadOnlySpan span) ? + Average(span, selector) : + AverageEnumerable(source, selector); + } + + private static TResult? Average(ReadOnlySpan span, Func selector) + where TSelector : struct, INumber + where TAccumulator : struct, INumber + where TResult : struct, INumber + { + TAccumulator sum = TAccumulator.Zero; + long count = 0; + foreach (TSource item in span) + { + if (selector(item) is TSelector value) + { + // As in the enumerator-based loop, the sum starts from the first value rather than from zero. + // That is done in this one loop, rather than in a loop that finds the first value followed + // by another for the rest, as the selected value is then kept in registers. + TAccumulator converted = TAccumulator.CreateChecked(value); + if (count == 0) + { + sum = converted; + } + else + { + checked { sum += converted; } + } + + count++; + } + } + + if (count == 0) + { + return null; + } + + return TResult.CreateChecked(sum) / TResult.CreateChecked(count); + } + + private static TResult? AverageEnumerable(IEnumerable source, Func selector) + where TSelector : struct, INumber + where TAccumulator : struct, INumber + where TResult : struct, INumber + { using IEnumerator e = source.GetEnumerator(); while (e.MoveNext()) { diff --git a/src/libraries/System.Linq/tests/AverageTests.cs b/src/libraries/System.Linq/tests/AverageTests.cs index 6c3920d65c70eb..682a33c27d6dba 100644 --- a/src/libraries/System.Linq/tests/AverageTests.cs +++ b/src/libraries/System.Linq/tests/AverageTests.cs @@ -660,5 +660,97 @@ public void Float_WithSelector() Assert.Equal(expected, source.Average(e => e.num)); } + + [Theory] + [InlineData(1)] + [InlineData(2)] + [InlineData(100)] + public void Average_Selector_AllSourceTypes_ProperAverageReturned(int count) + { + // The first item has no value, so the nullable overloads have to skip to the first one that does. + (int Value, bool HasValue)[] items = Enumerable.Range(1, count).Select(i => (i, i % 3 != 1)).ToArray(); + + long sum = 0; + long nullableSum = 0; + int nullableCount = 0; + foreach ((int value, bool hasValue) in items) + { + sum += value; + if (hasValue) + { + nullableSum += value; + nullableCount++; + } + } + + double expected = (double)sum / count; + decimal expectedDecimal = (decimal)sum / count; + double? expectedNullable = nullableCount == 0 ? null : (double)nullableSum / nullableCount; + decimal? expectedNullableDecimal = nullableCount == 0 ? null : (decimal)nullableSum / nullableCount; + + foreach (IEnumerable<(int Value, bool HasValue)> source in CreateSources(items)) + { + Assert.Equal(expected, source.Average(x => x.Value)); + Assert.Equal(expected, source.Average(x => (long)x.Value)); + Assert.Equal((float)expected, source.Average(x => (float)x.Value)); + Assert.Equal(expected, source.Average(x => (double)x.Value)); + Assert.Equal(expectedDecimal, source.Average(x => (decimal)x.Value)); + + Assert.Equal(expectedNullable, source.Average(x => x.HasValue ? x.Value : (int?)null)); + Assert.Equal(expectedNullable, source.Average(x => x.HasValue ? x.Value : (long?)null)); + Assert.Equal((float?)expectedNullable, source.Average(x => x.HasValue ? x.Value : (float?)null)); + Assert.Equal(expectedNullable, source.Average(x => x.HasValue ? x.Value : (double?)null)); + Assert.Equal(expectedNullableDecimal, source.Average(x => x.HasValue ? x.Value : (decimal?)null)); + } + } + + [Fact] + public void Average_Selector_AllSourceTypes_NoValues() + { + foreach (IEnumerable source in CreateSources(Array.Empty())) + { + Assert.Throws(() => source.Average(x => x)); + Assert.Throws(() => source.Average(x => (long)x)); + Assert.Throws(() => source.Average(x => (float)x)); + Assert.Throws(() => source.Average(x => (double)x)); + Assert.Throws(() => source.Average(x => (decimal)x)); + + Assert.Null(source.Average(x => (int?)x)); + Assert.Null(source.Average(x => (long?)x)); + Assert.Null(source.Average(x => (float?)x)); + Assert.Null(source.Average(x => (double?)x)); + Assert.Null(source.Average(x => (decimal?)x)); + } + + foreach (IEnumerable source in CreateSources(new[] { 1, 2, 3 })) + { + Assert.Null(source.Average(x => (int?)null)); + Assert.Null(source.Average(x => (long?)null)); + Assert.Null(source.Average(x => (float?)null)); + Assert.Null(source.Average(x => (double?)null)); + Assert.Null(source.Average(x => (decimal?)null)); + } + } + + [Fact] + public void Average_Selector_AllSourceTypes_Overflow() + { + foreach (IEnumerable source in CreateSources(new[] { 1, 2 })) + { + Assert.Throws(() => source.Average(x => long.MaxValue)); + Assert.Throws(() => source.Average(x => (long?)long.MaxValue)); + Assert.Throws(() => source.Average(x => decimal.MaxValue)); + Assert.Throws(() => source.Average(x => (decimal?)decimal.MaxValue)); + + // Int32 and Single values are added up in a wider type, so their sum doesn't overflow. + Assert.Equal((double)int.MaxValue, source.Average(x => int.MaxValue)); + Assert.Equal((double?)int.MaxValue, source.Average(x => (int?)int.MaxValue)); + Assert.Equal(float.MaxValue, source.Average(x => float.MaxValue)); + Assert.Equal((float?)float.MaxValue, source.Average(x => (float?)float.MaxValue)); + + Assert.True(double.IsPositiveInfinity(source.Average(x => double.MaxValue))); + Assert.True(double.IsPositiveInfinity(source.Average(x => (double?)double.MaxValue).Value)); + } + } } }