我有一个列表,我想每次都按随机顺序排序。
我遇到了几种方法:
list = list.OrderBy(x => Guid.NewGuid()).ToList();
var rnd = new Random(); myList = myList.OrderBy(x => rnd.Next()).ToList();
static Random random = new Random(); public static IEnumerable<T> RandomPermutation<T>(IEnumerable<T> sequence) { T[] retArray = sequence.ToArray(); for (int i = 0; i < retArray.Length - 1; i += 1) { int swapIndex = random.Next(i + 1, retArray.Length); T temp = retArray[i]; retArray[i] = retArray[swapIndex]; retArray[swapIndex] = temp; } return retArray; }
明明1和3的代码量差别很大,但是有什么好处吗?