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
Release: 2025-02-03 07:58:13
Original
1104 people have browsed it

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:

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

<方法> How to use:

List<Product> products = GetProducts();
products.Shuffle();
Copy after login
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

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

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))); }
    }
}
Copy after login
Integrate the thread security method to the shuffle extension method:

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