Super Simple Array Shuffle with LINQ

Thomas Steffen
2 min readDec 1, 2023

--

Recently I was working on a project and I needed to randomize the contents of an array. Previously, I used the Knuth Shuffle, which worked. But having done some more research, I was able to create a very dynamic, shortly written, and easy to use method.

In this example, I am using this shuffle in Unity using C#. I will use the following namespaces:

using System;
using System.Linq;

By utilizing LINQ’s ordering and the Random class within the System namespace, we can create some short efficient code.

static T[] ShuffleArray<T>(T[] array)
{
System.Random random = new System.Random();
return array.OrderBy(x => random.Next()).ToArray();
}

Initially I had this as a static void, but in order to modify the original array instead of just a copy of the array, I had to convert this to a generic method, which in the end, made it more dynamic in use.

The method works with array of any type, “T”. Alternatively, I could have specified this using ShuffleArray(Transform[] array){…}, or another type, but creating this in a dynamic way really allows the use of this system in any needed case.

Instead of using Random random, I specified that this is the System.Random random. In my case, I am working in the Unity engine, so I am also using UnityEngine namespace, which contains it’s own separate Random class. The UnityEngine.Random is different than the System.Random.

Next, I utilized LINQ’s OrderBy method to the elemnts of the array. Sorting is generated by random.Next() for each element x in the array, which effectively shuffles the array. Then, ToArray() converts the new ordered sequence back into an array.

Now this still creates a ‘copy’ of the array. In order to re-assign this shuffle to the currently used array, we would have to call it like this:

[SerializeField] private Transform[] _enemyWaypoints;

private void Start()
{
_enemyWaypoints = ShuffleArray(_enemyWaypoints);
}

When the code is executed at Start(), you should now see the ‘_enemyWaypoints’ array in a new randomized order.

Before running the Shuffle
After running the Shuffle

--

--

Thomas Steffen
Thomas Steffen

Written by Thomas Steffen

I am Virtual Reality Developer, UI Systems, and general programmer with a passion for Unity software development.

Responses (1)