Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions src/libraries/System.Linq/src/System/Linq/Average.cs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,38 @@ private static TResult Average<TSource, TSelector, TAccumulator, TResult>(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<TSource> span) ?
Average<TSource, TSelector, TAccumulator, TResult>(span, selector) :
AverageEnumerable<TSource, TSelector, TAccumulator, TResult>(source, selector);
}

private static TResult Average<TSource, TSelector, TAccumulator, TResult>(ReadOnlySpan<TSource> span, Func<TSource, TSelector> selector)
where TSelector : struct, INumber<TSelector>
where TAccumulator : struct, INumber<TAccumulator>
where TResult : struct, INumber<TResult>
{
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<TSource, TSelector, TAccumulator, TResult>(IEnumerable<TSource> source, Func<TSource, TSelector> selector)
where TSelector : struct, INumber<TSelector>
where TAccumulator : struct, INumber<TAccumulator>
where TResult : struct, INumber<TResult>
{
using IEnumerator<TSource> e = source.GetEnumerator();
if (!e.MoveNext())
{
Expand Down Expand Up @@ -235,6 +267,52 @@ private static TResult Average<TSource, TSelector, TAccumulator, TResult>(this I
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.selector);
}

return source.TryGetSpan(out ReadOnlySpan<TSource> span) ?
Average<TSource, TSelector, TAccumulator, TResult>(span, selector) :
AverageEnumerable<TSource, TSelector, TAccumulator, TResult>(source, selector);
}

private static TResult? Average<TSource, TSelector, TAccumulator, TResult>(ReadOnlySpan<TSource> span, Func<TSource, TSelector?> selector)
where TSelector : struct, INumber<TSelector>
where TAccumulator : struct, INumber<TAccumulator>
where TResult : struct, INumber<TResult>
{
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<TSource, TSelector, TAccumulator, TResult>(IEnumerable<TSource> source, Func<TSource, TSelector?> selector)
where TSelector : struct, INumber<TSelector>
where TAccumulator : struct, INumber<TAccumulator>
where TResult : struct, INumber<TResult>
{
using IEnumerator<TSource> e = source.GetEnumerator();
while (e.MoveNext())
{
Expand Down
92 changes: 92 additions & 0 deletions src/libraries/System.Linq/tests/AverageTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<int> source in CreateSources(Array.Empty<int>()))
{
Assert.Throws<InvalidOperationException>(() => source.Average(x => x));
Assert.Throws<InvalidOperationException>(() => source.Average(x => (long)x));
Assert.Throws<InvalidOperationException>(() => source.Average(x => (float)x));
Assert.Throws<InvalidOperationException>(() => source.Average(x => (double)x));
Assert.Throws<InvalidOperationException>(() => 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<int> 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<int> source in CreateSources(new[] { 1, 2 }))
{
Assert.Throws<OverflowException>(() => source.Average(x => long.MaxValue));
Assert.Throws<OverflowException>(() => source.Average(x => (long?)long.MaxValue));
Assert.Throws<OverflowException>(() => source.Average(x => decimal.MaxValue));
Assert.Throws<OverflowException>(() => 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));
}
}
}
}
Loading