要获得一个随机数据,最简单的方法是使用 Random 类型:
https://learn.microsoft.com/zh-cn/dotnet/api/system.random?view=net-7.0
如果要从一个数组中随机取出一条数据,可以使用以下代码:
Random rnd = new Random(); string[] malePetNames = { "Rufus", "Bear", "Dakota", "Fido", "Vanya", "Samuel", "Koani", "Volodya", "Prince", "Yiska" }; string[] femalePetNames = { "Maggie", "Penny", "Saya", "Princess", "Abby", "Laila", "Sadie", "Olivia", "Starlight", "Talla" }; // Generate random indexes for pet names. int mIndex = rnd.Next(malePetNames.Length); int fIndex = rnd.Next(femalePetNames.Length); // Display the result. Console.WriteLine("Suggested pet name of the day: "); Console.WriteLine(" For a male: {0}", malePetNames[mIndex]); Console.WriteLine(" For a female: {0}", femalePetNames[fIndex]); // The example displays output similar to the following: // Suggested pet name of the day: // For a male: Koani // For a female: Maggie
如果想要对数组或列表的内容进行随机排序,可以使用以下代码:
public static void Shuffle<T>(Random rnd, T[] array) { int n = array.Length; while (n > 1) { int k = rnd.Next(n--); T temp = array[n]; array[n] = array[k]; array[k] = temp; } } public static void Shuffle<T>(Random rnd, IList<T> array) { int n = array.Count; while (n > 1) { int k = rnd.Next(n--); T temp = array[n]; array[n] = array[k]; array[k] = temp; } }
以上代码使用了一种名为“Knuth Shuffle”(又名 Fisher–Yates shuffle)的算法,时间复杂度为 O(n) 。
简单来说 Knuth Shuffle 算法是一个用来将一个有限集合生成一个随机排列的算法(数组随机排序)。这个算法生成的随机排列是等概率的。同时这个算法非常高效。
如果你对这个算法感兴趣,可以看看这篇文章:
https://gaohaoyang.github.io/2016/10/16/shuffle-algorithm/
具体的调用方法如下:
var arr = new int[] { 1,2,3,4,5,6 }; var rnd = new Random(); Shuffle(rnd, arr); Console.WriteLine(string.Join(", ", arr));