/// <summary> /// 生成隨機索引列表 /// </summary> /// <param name="maxNumber"></param> /// <returns></returns> private static List<int> CreateRandomNumbers(int maxNumber) { var array = new int[maxNumber]; for (var i = 0; i < maxNumber; i++) { array[i] = i; } var rnd = new Random(); for (var i = 0; i < maxNumber; i++) { var index = rnd.Next(0, maxNumber); if (i != index) { var tmpval = array[i]; array[i] = array[index]; array[index] = tmpval; } } var list = new List<int>(); for (var i = 0; i < maxNumber; i++) { list.Add(array[i]); } return list; } /// <summary> /// 生成隨機索引列表 /// </summary> /// <param name="maxNumber"></param> /// <returns></returns> private static List<int> CreateRandomNumbers2(int maxNumber) { List<int> list = new List<int>(); Random rd = new Random(); while (list.Count() < maxNumber) { int i = rd.Next(0, maxNumber); if (!list.Contains(i)) { list.Add(i); } } return list; } /// <summary> /// 生成隨機索引列表 /// </summary> /// <param name="maxNumber"></param> /// <returns></returns> private static List<int> CreateRandomNumbers2(int maxNumber) { var array = new int[maxNumber, 2]; var index = maxNumber - 1; var rnd = new Random(); while (index > 0) { array[index, 0] = index; array[index, 1] = rnd.Next(0, maxNumber); index--; } var list = new List<int>(); for (var i = 0; i < maxNumber; i++) { for (var j = i + 1; j < maxNumber; j++) { if (array[i, 1] > array[j, 1]) { var tIndex = array[i, 0]; var tValue = array[i, 1]; array[i, 0] = array[j, 0]; array[i, 1] = array[j, 1]; array[j, 0] = tIndex; array[j, 1] = tValue; } } } for (var i = 0; i < maxNumber; i++) { list.Add(array[i, 0]); } return list; }
第一種速度最快,第二種次之,第三種最慢