Do you want to Shuffle A List In C#?
In this blog post, we will show you how you can shuffle a list in C# using the Random function.
I remember creating a shuffle method when I was creating a poker application and needed to shuffle a list of cards from a deck.
I had to use the Math.Random method to randomly pick a card from the list of cards and then assign them to a new list.
Let's see this in action.
Shuffle A List In C# Using Math.Random() Method
As we know, we can use the Math.Random() method and it gives us a random integer out of the given range.
We will make use of this Math.Random method to shuffle list in C#.
Let's look at some code.
public static void Main()
{
// List Of Integers From 1 TO 20
var listOfNumbersInOrder = new List
Result:
// A random and shuffled result (will be totally different next time you run the function) 3 14 15 5 6 4 9 16 17 19 18 8 1 13 10 11 20 2 12 7
As we can see in the code example above, we loop through the list 20 times (which is the count of items in the list).
Every time, we take a random number and then pick an element from the list. We use this element to create a new shuffled list.
This way, we can make sure that the list is a shuffled list everytime.
Shuffle List Of Strings In C# Using Math.Random() Method
Just how we used the above method to create a ShuffleList() method, this time, we will go one step ahead and we will create a generic method which will shuffle any list (not just shuffle a list of strings)
Let's use C# generics and shuffle a list.
public static void Main()
{
var listOfStringsInOrder = new List
Result:
// A random and shuffled result (will be totally different next time you run the function) three four one two five
Now that we have created a generic method, we can shuffle a list of any type in C# using this method.