A Simple Way to Shuffle Your Lists in C#

Did you ever need a little bit of randomness in a list? Not cryptographically strong randomness, just a bit of unpredictability so that not every run of your tool is the same? If so, this post offers you a simple way to shuffle your lists.

If you google for a solution, you find many complex examples using random number generators. Those approaches are fine, but I can’t remember them and have to start from scratch every time I need to shuffle my lists. In my latest attempt I found an interesting approach by user453230 in his answer to this question on Stack Overflow:

This snipped orders a list by a newly created GUID and turns the result into a new list. A GUID is a globally unique identifier, maybe a bit too much for our task, yet it is easy to remember.

This code snippet is not a general-purpose solution, but it may help you for far more than you expect. Some may point out the performance cost of a GUID. Years ago, this was the source of many debates. With faster machines and a highly optimised .Net framework this is no longer a big problem – as long as your lists don’t get too big. I can create one million GUIDs in less than 0.2 seconds on my laptop. If you need to get the most out of your code, this is too slow and you may need a more complex solution. However, for most day-to-day tasks this is fast enough. As with all other performance related tasks: Measure first!

2 thoughts on “A Simple Way to Shuffle Your Lists in C#”

  1. Thanks a lot, I was looking for something like List.Shuffle(), but this simple solution did the trick!

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.