Shuffling C# generic lists

Just a quick hack for shuffling generic lists in C# like this one:

List<T> list

You may use proper solutions like those in this StackOverflow thread, if you need it for something serious, or simply do this:

list.Sort ((x, y) => Random.value < 0.5f ? -1 : 1)

which simply defines a sorting function that randomly returns -1 or 1 when comparing two elements, shuffling the original list.

I’m not exactly sure if this is right, but it works! If there’s a reason why this is not a good idea, please share it!

Leave a Reply

Your email address will not be published. Required fields are marked *