#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))


About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #565 – Using an Iterator to Return A Shuffled Sequence

  1. mstum says:

    Small suggestion: GUIDs happen to be mostly random in the current implementation of the .net Framework (they lose at least 4 bits of entropy because of the hardcoded version 4 part), but they don’t have to be, they are only expected to be unique, not random. A possibly more appropriate version would use a static new Random() and order by Random.Next(), since that’s intended to be the random number generator. See Eric Lipperts comment on http://stackoverflow.com/questions/10178299

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: