Start Debugging

C# Randomly choose items from a list

In C#, you can randomly select items from a list using Random.GetItems, a method introduced in .NET 8. Learn how it works with practical examples.

In C#, you can randomly select items from a list using Random.GetItems, a method introduced in .NET 8.

public T[] GetItems<T>(T[] choices, int length)

The method takes in two parameters:

There are two important things to note about this method:

With all this being said, let’s take a few examples. Let’s assume the following array of choices:

string[] fruits =
[
    "apple",
    "banana",
    "orange",
    "kiwi"
];

For selecting 2 random fruits from that list, we simply call:

var chosen = Random.Shared.GetItems(fruits, 2);

Now, as I’ve said before, the two chosen fruits are not necessarily unique. You could end up for example with [ "kiwi", "kiwi" ] as your chosen array. You can test this out easily with a do-while:

string[] chosen = null;

do
    chosen = Random.Shared.GetItems(fruits, 2);
while (chosen[0] != chosen[1]);

// At this point, you will have the same fruit twice

And this opens the method up for selecting more items than you actually have in the list. In our example we have only 4 fruits to choose from, but we can ask GetItems to choose 10 fruits for us, and it will happily do it.

var chosen = Random.Shared.GetItems(fruits, 10);
// [ "kiwi", "banana", "kiwi", "orange", "apple", "orange", "apple", "orange", "kiwi", "apple" ]
< Back