diff --git a/MoreLinq/RandomSubset.cs b/MoreLinq/RandomSubset.cs index f5f0de015..3bb1decc8 100644 --- a/MoreLinq/RandomSubset.cs +++ b/MoreLinq/RandomSubset.cs @@ -61,10 +61,10 @@ public static IEnumerable RandomSubset(this IEnumerable source, int sub if (source == null) throw new ArgumentNullException(nameof(source)); if (subsetSize < 0) throw new ArgumentOutOfRangeException(nameof(subsetSize)); - return RandomSubsetImpl(source, rand, seq => (seq.ToArray(), subsetSize)); + return RandomSubsetImpl(source, rand, subsetSize); } - static IEnumerable RandomSubsetImpl(IEnumerable source, Random rand, Func, (T[], int)> seeder) + static IEnumerable RandomSubsetImpl(IEnumerable source, Random rand, int? subsetSize) { // The simplest and most efficient way to return a random subset is to perform // an in-place, partial Fisher-Yates shuffle of the sequence. While we could do @@ -72,15 +72,14 @@ static IEnumerable RandomSubsetImpl(IEnumerable source, Random rand, Fu // than the length of the sequence. // See: http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle - var (array, subsetSize) = seeder(source); + var array = source.ToArray(); + subsetSize ??= array.Length; if (array.Length < subsetSize) { -#pragma warning disable CA2208 // Instantiate argument exceptions correctly - // TODO Throw InvalidOperationException instead? + // TODO Throw InvalidOperationException instead? throw new ArgumentOutOfRangeException(nameof(subsetSize), "Subset size must be less than or equal to the source length."); -#pragma warning restore CA2208 // Instantiate argument exceptions correctly } var m = 0; // keeps track of count items shuffled diff --git a/MoreLinq/Shuffle.cs b/MoreLinq/Shuffle.cs index c7cac7d6e..dad62d3bf 100644 --- a/MoreLinq/Shuffle.cs +++ b/MoreLinq/Shuffle.cs @@ -19,7 +19,6 @@ namespace MoreLinq { using System; using System.Collections.Generic; - using System.Linq; public static partial class MoreEnumerable { @@ -70,11 +69,7 @@ public static IEnumerable Shuffle(this IEnumerable source, Random rand) if (source == null) throw new ArgumentNullException(nameof(source)); if (rand == null) throw new ArgumentNullException(nameof(rand)); - return RandomSubsetImpl(source, rand, seq => - { - var array = seq.ToArray(); - return (array, array.Length); - }); + return RandomSubsetImpl(source, rand, subsetSize: null); } } }