What is the best way to randomize the order of a generic list in C#? I've got a finite set of 75 numbers in a list I would like to assign a random order to, in order to draw them for a lottery type application.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
A simple modification of the accepted answer that returns a new list instead of working in-place, and accepts the more general
IEnumerable<T>
as many other Linq methods do.Old post for sure, but I just use a GUID.
A GUID is always unique, and since it is regenerated every time the result changes each time.
Shuffle any
(I)List
with an extension method based on the Fisher-Yates shuffle:Usage:
The code above uses the much criticised System.Random method to select swap candidates. It's fast but not as random as it should be. If you need a better quality of randomness in your shuffles use the random number generator in System.Security.Cryptography like so:
A simple comparison is available at this blog (WayBack Machine).
Edit: Since writing this answer a couple years back, many people have commented or written to me, to point out the big silly flaw in my comparison. They are of course right. There's nothing wrong with System.Random if it's used in the way it was intended. In my first example above, I instantiate the rng variable inside of the Shuffle method, which is asking for trouble if the method is going to be called repeatedly. Below is a fixed, full example based on a really useful comment received today from @weston here on SO.
Program.cs:
EDIT The
RemoveAt
is a weakness in my previous version. This solution overcomes that.Note the optional
Random generator
, if the base framework implementation ofRandom
is not thread-safe or cryptographically strong enough for your needs, you can inject your implementation into the operation.A suitable implementation for a thread-safe cryptographically strong
Random
implementation can be found in this answer.Here's an idea, extend IList in a (hopefully) efficient way.I usually use:
If we only need to shuffle items in a completely random order (just to mix the items in a list), I prefer this simple yet effective code that orders items by guid...