Click here to Skip to main content
13,299,298 members (61,995 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


7 bookmarked
Posted 7 Apr 2009

Shuffling arrays in C#

, 7 Apr 2009
Rate this:
Please Sign up or sign in to vote.
Shuffling arrays in C#

Have you ever had a need to output some array of objects in a random order? Say an array of strings ... with 52 elements that each represent a playing card?

Well, if you have ever had a need to shuffle the elements in an array, you have probably found that there are only a few different algorithms: Either card swapping or assigning a random Key to each element and then sorting by the key.

Unfortunately there are quite a few issues involved with the swap shuffle, so I wanted to use the sort version. Well, what has tuples? Hashtables? Hashtables! So, how do you sort a Hashtable? Hmmmm, maybe I need to think harder about this.

Hey, did everyone realize there is a sorted version called a SortedList?

OK, so we will use the SortedList. Now I want this function to use Generics so that it will take an array of any type. So let's try!

(Mind you that this is not nearly as small as the implementation here but I am not posting here to show how to shuffle in the least number of lines or use the latest technology, but with an eye towards the most understandable source.)

private static T[] Shuffle <T> (T[] OriginalArray)
    var matrix = new SortedList();
    var r = new Random();

    for (var x = 0; x <= OriginalArray.GetUpperBound(0); x++)
        var i = r.Next();

        while (matrix.ContainsKey(i)) { i = r.Next(); }

        matrix.Add(i, OriginalArray[x]);

    var OutputArray = new T[OriginalArray.Length];

    matrix.Values.CopyTo(OutputArray, 0);

    return OutputArray;


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Web Developer
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMy vote of 1 Pin
Toli Cuturicu13-Nov-09 11:45
memberToli Cuturicu13-Nov-09 11:45 
GeneralMy vote of 1 Pin
abolibibelot8-Apr-09 6:03
memberabolibibelot8-Apr-09 6:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171207.1 | Last Updated 7 Apr 2009
Article Copyright 2009 by saunderl
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid