>隨機化C#列表
在這裡,
<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>
>rng
隨機數生成選項Random
標準類對於許多應用程序就足夠了。 但是,對於要求更高加密安全性和提高隨機性的情況
此版本使用來增強隨機性。 請注意添加的檢查以確保生成的隨機數在所需的範圍內。
System.Random
System.Security.Cryptography
>用法示例
<code class="language-csharp">public static void Shuffle<T>(this IList<T> list) { using (var provider = new RNGCryptoServiceProvider()) { int n = list.Count; while (n > 1) { byte[] box = new byte[1]; do provider.GetBytes(box); while (!(box[0] < (byte)((n + 1) * (double.MaxValue / 256)))); //Ensure value within range int k = box[0] % (n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } }</code>
兩種方法均使用相同的使用:RNGCryptoServiceProvider
性能注意事項
<>>提供速度,
提供了出色的隨機性,但以性能為代價。 根據應用程序的需求選擇適當的方法。 對於大多數通用的改組,<code class="language-csharp">List<Product> products = GetProducts(); products.Shuffle(); </code>是完全足夠的。
>
以上是如何在C#中隨機隨機洗牌?的詳細內容。更多資訊請關注PHP中文網其他相關文章!