OrderBy
uses the returned value to order items in ascending order. Suppose you had this scenario.
var numbers = new [] { 3, 5, 8, 10, 4, 2 };
var ordered = numbers.OrderBy(x => x);
In this case the numbers would be returned ordered by their value ascending (2, 3, 4, 5, 8, 10
). That's how OrderBy
works. It doesn't matter where the value comes from, it simply orders the items based upon value returned for each item.
In your specific case you are returning a random number each time. Therefore the items will be randomly ordered when they are returned.
var randomOrder = numbers.Shuffle();
This might return 2, 8, 3, 5, 10, 4
or 3, 8, 5, 4, 10, 3
. The order is completely determined by the randomness of the values generated. But do note that we generally assume consistent ordering so the order that the values are returned in can change each time the enumerator (that is returned by Shuffle
) is called. In this example it is called one time.
foreach (var result in numbers.Shuffle())
{
};
But look at this case.
var randomOrder = numbers.Shuffle();
var results1 = randomOrder.ToArray();
var results2 = randomOrder.ToArray();
Here the returned enumerator is called multiple times and each time it orders the items again. Given that the ordering is random results1
will produce a different ordering then results2
.
Given your purpose there is nothing wrong with this Shuffle
method. It is doing what you might expect if you were, say, shuffling a deck of cards.