Home >Backend Development >C++ >How Can I Efficiently Get a Random Subset from a Collection Using LINQ?
Optimizing LINQ: Obtaining a Random Shuffled Sub-Collection
Determining efficient methods for retrieving random subsets of a larger collection is a common challenge in programming. For LINQ queries, one approach is to leverage the Shuffle() extension method.
The Shuffle Method:
The Shuffle() method takes an IEnumerable collection as its input and returns a shuffled version of it. This method is particularly useful when one needs to obtain a random order of the elements in a collection.
Fisher-Yates-Durstenfeld Shuffle:
The Shuffle() method employs the Fisher-Yates-Durstenfeld shuffle algorithm, which provides a robust and efficient means of shuffling a collection. This algorithm involves iterating through the collection while randomly swapping elements with subsequent elements.
LINQ Extension Method:
Below is a LINQ-friendly extension method that implements the Fisher-Yates-Durstenfeld shuffle for use with IEnumerable collections:
public static class EnumerableExtensions { public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source) { return source.Shuffle(new Random()); } 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]; } } }
Usage:
To utilize the Shuffle() method, you can simply call it on your desired collection:
var yourCollection = new List<int> { 1, 2, 3, 4, 5 }; var randomItems = yourCollection.Shuffle().Take(3);
This will yield a shuffled collection of 3 random items from yourCollection. By default, the Shuffle() method uses a new Random() instance for randomization. You can also specify a custom Random instance for custom shuffling behavior.
The above is the detailed content of How Can I Efficiently Get a Random Subset from a Collection Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!