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

How to Efficiently Generate Random Subcollections Using LINQ?

Mary-Kate Olsen
Release: 2025-01-01 03:54:09
Original
978 people have browsed it

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];
        }
    }
}
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template