Randomize a List in C#
This post will discuss how to randomize a List in C#.
1. Using Enumerable.OrderBy Method
The Enumerable.OrderBy method sorts the elements of a sequence using the specified comparer. We can tweak it as follows to shuffle items in random order by using a random number generator. Note that this creates a shuffled copy of the source list and leaves the source list unchanged.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> values = new List<int>() { 1, 2, 3, 4, 5 }; Random rand = new Random(); var shuffled = values.OrderBy(_ => rand.Next()).ToList(); Console.WriteLine(String.Join(", ", shuffled)); } } |
2. Using Loop
To in-place randomize a list, we can write an extension method based on the Fisher–Yates shuffle algorithm. This can be implemented as follows in C#.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
using System; using System.Linq; using System.Collections.Generic; public static class Extensions { private static Random rand = new Random(); public static void Shuffle<T>(this IList<T> values) { for (int i = values.Count - 1; i > 0; i--) { int k = rand.Next(i + 1); T value = values[k]; values[k] = values[i]; values[i] = value; } } } public class Example { public static void Main() { List<int> values = new List<int>() { 1, 2, 3, 4, 5 }; values.Shuffle(); Console.WriteLine(String.Join(", ", values)); } } |
That’s all about randomizing a List in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)