打乱一组数组或集合中的元素顺序
/// <summary> /// 随机打乱一个int 数组 /// </summary> /// <param name="ints"></param> /// <returns></returns> public static int[] GetRdomArr(int[] ints) { int[] newInts = new int[ints.Length]; int total = ints.Length; int dex = 0; for (int i = 0; i < total; i++) { int index = new Random().Next(0, ints.Length); int rdom = ints[index]; if (!newInts.Contains(rdom)) { newInts[dex] = rdom; dex++; } else { total++; } } if (dex == ints.Length) { return newInts; } return newInts; }
List<int> lst = new List<int>() { 23, 22, 12, 254, 89, 15 }; int[] ints = GetRdomArr(lst.ToArray()); for (int i = 0; i < ints.Length; i++) { Console.WriteLine(ints[i]); }