Home >Backend Development >C++ >How Can I Randomly Shuffle a Generic List in C# Efficiently and Safely?
The random sorting of the generic list of generics
Fisher-Yates shuffle expansion method
by repeating the elements with random indexes. The following code block demonstrates an extension method to implement the Fisher-Yates algorithm:
<code class="language-csharp">private static Random rng = new Random(); 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>To use this expansion method, just call the shuffle () for iList
. For example:
<code class="language-csharp">List<Product> products = GetProducts(); products.Shuffle();</code>Use System.Security.Cryptography to improve randomness
<code class="language-csharp">using System.Security.Cryptography; ... 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)uint.MaxValue / uint.MaxValue * n))); int k = (int)(box[0] % n); T value = list[k]; list[k] = list[n - 1]; list[n - 1] = value; } } }</code>The importance of performance considerations and thread security
Conclusion
The above is the detailed content of How Can I Randomly Shuffle a Generic List in C# Efficiently and Safely?. For more information, please follow other related articles on the PHP Chinese website!