shuffle(随机重新排列)List

我需要重新排列我的List数组,它中包含不可确定数量的元素。

有人能举例说明我是怎么做到的,谢谢

 List source = ... var rnd = new Random(); var result = source.OrderBy(item => rnd.Next()); 

显然,如果你想要真正的随机性而不是伪随机数生成器,你可以使用RNGCryptoServiceProvider而不是Random 。

这是一个将随机播放List的扩展方法:

  public static void Shuffle(this IList list) { int n = list.Count; Random rnd = new Random(); while (n > 1) { int k = (rnd.Next(0, n) % n); n--; T value = list[k]; list[k] = list[n]; list[n] = value; } }