Home >Backend Development >C++ >How Can I Efficiently Shuffle a Generic List in C#?
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#.
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
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!