It is more efficient to use an algorithm like Fisher-Yates shuffle to reorder the items. The run-time complexity of OrderBy
is O(N log N)
while Fisher-Yates shuffle is O(N)
.
Also, to provide random numbers you should use the Random
class, not Guid.NewGuid
which serves a completely different purpose and just happens to create something that is random (at a higher cost).
I prefer to implement the shuffle as an extension method:
public static class ListExtensions
{
public static IList<T> Shuffle<T>(this IList<T> list, Random random)
{
for (var i = list.Count; i > 1; i -= 1)
{
var j = random.Next(i);
var temp = list[j];
list[j] = list[i - 1];
list[i - 1] = temp;
}
return list;
}
}
You can achieve the desired result by providing a Random
instance with a specific seed (in this case 0). This will ensure that the sequence of random numbers generated are the same each time the code executes:
var shuffledList = Enumerable.Range(0, 1000).ToList().Shuffle(new Random(0));