#565 – Using an Iterator to Return A Shuffled Sequence

The System.Linq namespace includes an OrderBy method that makes it easy to reorder an enumerable sequence, based on a particular key.  For a key, we can use a newly generated Guid to achieve a random order.  (See Jeff Atwood’s post on Shuffling).

We can encapsulate this shuffling behavior in a method that returns the resulting shuffled sequence as an IEnumerable. We’ll use an iterator in the body of this method to return the shuffled sequence of elements.

        // Two line shuffle
        static IEnumerable<int> Shuffle(List<int> theList)
            foreach (int next in theList.OrderBy(x => Guid.NewGuid()))
                yield return next;

You can now use this method to iterate through the original sequence in a random order.  You can also view this as moving through a newly shuffled sequence.  Note that the original list is not re-ordered.

            List<int> myList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            foreach (int i in Shuffle(myList))