What is the best way to randomize an array of strings with .NET? My array contains about 500 strings and I’d like to create a new Array with the same strings but in a random order.
Please include a C# example in your answer.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First, you should use the most upvoted answer to this question so far, which is https://stackoverflow.com/a/110570/1757994.
You can shuffle using LINQ.
var myShuffledArray = myArray.Shuffle().Add the following code as a file called
EnumerableExtensions.csto your project:Adapted from https://github.com/microsoft/driver-utilities/blob/master/src/Sarif.Driver/EnumerableExtensions.cs
It is a bad idea to use informally authored shuffle algorithms, since they are hard to analyze for flaws.
If you’re using C# 7.0 or higher, this other approach is slow for many elements but works correctly in all environments C# is used:
This is almost as verbose as the Fisher-Yates shuffle, which is much faster for large numbers of elements. This creates random numbers for each element, then sorts by the random number.
This answer used to say something along the lines of
.OrderBy(x => random()).Experienced developers will correctly know that
.OrderBy(x => random())alone is wrong. So if you commit code that contains it, you will look bad.Why is it wrong? OrderBy expects the keySelector, the function that it is passed, to be pure. That means the keySelector should return the same answer every time it is called and cause no side effects.
C# implementations like Unity’s do not cache the result of the selector passed to OrderBy. Games tend to shuffle things. It is hard to generalize across all CLR implementations, so it’s better to just use the correct thing. In order to not look bad with code you author, you should use Fisher-Yates instead.
For Visual Basic and versions of C# earlier than 7.0, use Fisher-Yates. A correct implementation using only LINQ is more verbose than implementing Fisher-Yates, so you will have written more code to do a worse implementation.