Efficient and random sorting C#list
In C#, random sorting of generic lists is a common task in software development. For example, in lottery applications, you may need to be randomly sorted on limited digital sets.
Best Practice:
In C#, the most effective method for random setting lists is to use the expansion method based on the Fisher-Yates shuffling algorithm. The method provided below ensures efficient and truly randomly random reshuffle list elements:
How to use:
<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>
This extension method is simple. Consider the following example: The choice of random number generator:
Although the above code uses the
<code class="language-csharp">List<Product> products = GetProducts(); products.Shuffle();</code>
, as shown below:
thread security: System.Random
System.Security.Cryptography
In order to ensure the randomization of threads safely, the following modified expansion methods must be considered:
<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)byte.MaxValue * (double)n / (double)uint.MaxValue))); int k = (int)(box[0] / ((double)byte.MaxValue / n)); T value = list[k]; list[k] = list[n - 1]; list[n - 1] = value; } } }</code>
Among them defined as:
Through these methods, you can choose the most suitable random sorting method according to your needs. Please note that the importance of when usingto ensure the correct release of resources.
The above is the detailed content of How Can I Efficiently Shuffle a List in C#?. For more information, please follow other related articles on the PHP Chinese website!