1

How do I randomize the order of the files I get out of:

string[] files = Directory.GetFiles("folder");

Thank you! :-)

janhartmann
  • 14,713
  • 15
  • 82
  • 138

4 Answers4

5

One option is to use Random:

Random rng = new Random();

and then:

var randomOrderFiles = files.OrderBy(f => rng.Next());

This isn't the most efficient method as it takes O(nlogn). If this is a problem for you, better algorithms exist.

Kobi
  • 135,331
  • 41
  • 252
  • 292
2

If you can't use Linq the following method should work:

static Random rand = new Random();
static void Randomize<T>(IList<T> list)
{
    for (int i = list.Count - 1; i > 0; i--)
    {
        int i2 = rand.Next(i + 1);
        if (i2 != i)
        {
            T tmp = list[i2];
            list[i2] = list[i];
            list[i] = tmp;
        }
    }
}
Hans Olsson
  • 54,199
  • 15
  • 94
  • 116
  • aka [Fisher–Yates Shuffle](http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) - this can be done in-place (as you did), and has complexity of O(n). – Kobi May 25 '10 at 09:37
2

A Fisher-Yates-Durstenfeld shuffle is O(n) and should give unbiased distribution.

Create a helper/extension method to perform an in-place shuffle on the array returned from GetFiles:

// uses ShuffleInPlace extension from https://stackoverflow.com/a/5589250/55847
var arrayOfFiles = Directory.GetFiles("folder");
arrayOfFiles.ShuffleInPlace();

If you prefer to return a new sequence -- à la LINQ -- you could create a suitable Shuffle extension method instead:

// uses Shuffle extension from https://stackoverflow.com/a/1653204/55847
var sequenceOfFiles = Directory.EnumerateFiles("folder").Shuffle();
Community
  • 1
  • 1
LukeH
  • 263,068
  • 57
  • 365
  • 409
0
  1. Iterate over the source list.
  2. Remove a random source item from the source list
  3. Append removed item to a result list
  4. Repeat until the source list is empty

List<string> files = Directory.GetFiles("folder");
List<string> result = new List<string>();

while (files.Count > 0)
{
  int n = IntegerUtility.Random(files.Count);
  string file = files.Remove(n);
  result.Add(file);
} 
return result;

Rob
  • 5,525
  • 1
  • 24
  • 26