When dealing with large datasets, obtaining a random shuffled collection of a specific size from a given collection becomes crucial. This commonly arises in scenarios involving randomized selection or sampling. Let's explore an optimal LINQ-based solution to this problem.
The Fisher-Yates-Durstenfeld shuffle algorithm offers an efficient and reliable approach to random shuffling. In this context, the goal is to produce a random subset of size 'n' from a collection of 'N' elements, where 'n' is less than or equal to 'N.'
To implement this algorithm using LINQ, we can leverage an extension method that encapsulates the shuffle operation. The following code snippet provides a comprehensive implementation:
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]; } }
In this implementation, the Shuffle extension method accepts an input sequence source and an instance of Random named rng. It creates a buffer list from the input sequence and iterates through it, randomly selecting elements. The selected elements are returned as an iterator, preserving the random ordering.
To utilize this extension method, simply append .Shuffle() to the input sequence followed by .Take(n), where n represents the desired size of the shuffled subcollection. For instance:
var randomItems = yourCollection.Shuffle().Take(n);
This Linq-based approach provides a concise and efficient solution for randomly shuffling and obtaining a subcollection of any size from a given collection. It is particularly suited for scenarios where a true randomization is required.
The above is the detailed content of How Can I Randomly Shuffle a Subset of a Collection Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!