Home >Backend Development >C++ >How Can I Efficiently Shuffle a Generic List in C#?

How Can I Efficiently Shuffle a Generic List in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-02-03 07:58:131057browse

The efficient shuffle method of the generic list of generics

In various programming scenarios, the order of elements in randomly generic lists is a common operation. This article will introduce the best way to achieve this goal in C#.

Fisher-Yates shuffle algorithm implementation

The most recommended method is to use the Fisher-Yates shuffle algorithm, which is a well-known list randomization algorithm. To use this method, please define an extension method, as shown below:

<code class="language-csharp">public static void Shuffle<T>(this IList<T> list)  
{  
    int n = list.Count;  
    while (n > 1) {  
        n--;  
        int k = rng.Next(n + 1);  
        T value = list[k];  
        list[k] = list[n];  
        list[n] = value;  
    }  
}</code>

How to use:

<code class="language-csharp">List<Product> products = GetProducts();
products.Shuffle();</code>
Using System.Security.Cryptography to enhance randomness

Although high efficiency, it may not be able to generate a real random sequence. In order to improve the randomness, Library provides a more reliable option:

System.Random System.Security.Cryptography Thread security considerations

<code class="language-csharp">public static void Shuffle<T>(this IList<T> list)
{
    using (RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider())
    {
        int n = list.Count;
        while (n > 1)
        {
            byte[] box = new byte[1];
            do provider.GetBytes(box);
            while (!(box[0] < (byte)((double)n / 256))); //确保生成的随机数在范围内
            int k = (int)(box[0] * (n / 256.0));
            T value = list[k];
            list[k] = list[n - 1];
            list[n - 1] = value;
            n--;
        }
    }
}</code>
When using the SHUFFLE expansion method in multi -threaded applications, it is necessary to ensure thread security. A simple solution is to create a new example of

:

ThreadSafeRandom The updated expansion method

<code class="language-csharp">public static class ThreadSafeRandom
{
    [ThreadStatic] private static Random Local;

    public static Random ThisThreadsRandom
    {
        get { return Local ?? (Local = new Random(unchecked(Environment.TickCount * 31 + Thread.CurrentThread.ManagedThreadId))); }
    }
}</code>
Integrate the thread security method to the shuffle extension method:

<code class="language-csharp">public static void Shuffle<T>(this IList<T> list)
{
    int n = list.Count;
    while (n > 1)
    {
        n--;
        int k = ThreadSafeRandom.ThisThreadsRandom.Next(n + 1);
        T value = list[k];
        list[k] = list[n];
        list[n] = value;
    }
}</code>
This Revied Answer PROVIDES CLERERERERERERANPLANATIONS, Improves Code Readability (Especially The RngCryProvider Examph), and addresses threa d Safety Concerns More Effectively.

The above is the detailed content of How Can I Efficiently Shuffle a Generic List in C#?. 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