Randomize files output in folder
How do I randomize the order of the files I get out of:
string[] files = Directory.GetFiles("fol开发者_如何学JAVAder");
Thank you! :-)
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.
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;
}
}
}
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();
- Iterate over the source list.
- Remove a random source item from the source list
- Append removed item to a result list
- 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;
精彩评论