随机重新排列数组项 c#
本文关键字:数组 排列 新排列 随机 | 更新日期: 2023-09-27 17:56:20
我有一个包含从 1 到 100 的数字的 c# int 数组这意味着
myArray[0] = 1;
myArray[1] = 2;
....
myArray[99] = 100;
但是我想在这个数组中随机重新排列它们,在 c# 中可以吗?
使用 Random 和 Linq,您可以轻松完成:
Random r = new Random();
myArray = myArray.OrderBy(x => r.Next()).ToArray();
上面提供了使用 Random
对象为数组中的每个元素提供随机排序顺序。
您需要在文件顶部添加using System.Linq;
才能使用扩展OrderBy
方法。