Shuffle a List<T> in C# .NET 7 with one line

Athanasios Emmanouilidis
Level Up Coding
Published in
2 min readJul 12, 2023

--

Photo by Carson Arias on Unsplash

There will be a time in your programming career that you will need to shuffle a list of objects/primitives. This can be done easily using LINQ’s OrderBy() and Random.Next().

Let’s see the algorithm step by step:

  1. We declare the list.
// Declaration of list
List<int> listOfInt = new() {1, 2, 3, 4, 5};

2. We call Random.Shared.Next() which returns a random integer. We then pass this random integer as a parameter to OrderBy().
OrderBy() orders a list in ascending order according to a key.
Giving it our random integer as a key will make the list items to be ordered randomly. We call ToList() to get a new List<int> from it and save the result back to our list.

listOfInt = listOfInt.OrderBy(x=> Random.Shared.Next()).ToList();

3. We finally foreach the list and print our items.

foreach (int item in listOfInt)
{
Console.WriteLine(item);
}

/* Will output something like
3
2
5
4
1
*/

Here is the full code:

using System;
using System.Collections.Generic;
using System.Linq;

List<int> listOfInt = new() {1, 2, 3, 4, 5};

listOfInt = listOfInt.OrderBy(x=> Random.Shared.Next()).ToList();

foreach (int item in listOfInt)
{
Console.WriteLine(item);
}

/* Will output something like
3
2
5
4
1
*/

That’s it! You now know how to shuffle a List of objects/primitives in C# .NET7.

That was the end of the article! If you have any thought or questions on the article, feel free to leave a comment. If you found the article useful and want to read more like this, be sure to follow me! Also please share it with people you think will benefit from it. See you on the next one!

--

--

Software Engineer @ Intelligen, Inc. Specializes in Microsoft's .NET stack and related technologies. Cybersecurity enthusiast.