Optimal LINQ Query for Random Subcollections: Shuffle
Generating a random shuffled collection of specific count from a larger collection can be achieved in multiple ways using LINQ.
One efficient approach is to utilize the Fisher-Yates-Durstenfeld shuffle algorithm, which can be implemented as an extension method in LINQ:
public static class EnumerableExtensions { public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng) { if (source == null) throw new ArgumentNullException(nameof(source)); if (rng == null) throw new ArgumentNullException(nameof(rng)); return source.ShuffleIterator(rng); } private static IEnumerable<T> ShuffleIterator<T>( this IEnumerable<T> source, Random rng) { var buffer = source.ToList(); for (int i = 0; i < buffer.Count; i++) { int j = rng.Next(i, buffer.Count); yield return buffer[j]; buffer[j] = buffer[i]; } } }
To retrieve a random subcollection of count 'n' from a collection of 'N' items, where n <= N, simply apply the Shuffle() extension method followed by Take(n):
var randomItems = yourCollection.Shuffle().Take(n);
The above is the detailed content of How to Efficiently Generate Random Subcollections Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!