Home >Backend Development >C++ >How to Efficiently Generate Random Subcollections Using LINQ?

How to Efficiently Generate Random Subcollections Using LINQ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-01 03:54:09984browse

How to Efficiently Generate Random Subcollections Using LINQ?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn