What's new in .NET 8 for Random?
Publié le 20/03/2023
Par  Christophe MOMMER

.NET 8 is coming soon (november 2023), and the first preview brought us two handy methods to deal with random!

Shuffle a collection

The first method allows us to easily shuffle a collection. Why do we need that? In fact, among other things, for ML.NET, you will have better results if your collection is shuffled. You can also use this method if you want to create a new hangman game :

public string PickAWord()
{
   var words = new[] { "carrot", "computer", "island", "tomato", "mobile" };
   var pickedWord = Random.Shared.Shuffle(words).First();
}

Note that the Shuffle method doesn't return a new collection but shuffle the original one!

Get items randomly in a collection

The other handy method allows us to get a bunch of items randomly from a collection. Beware: this method will not guarantee that you have distinct words. But you can get as many items as you want, picked in a random manner.

public void PickThreeNumbers()
{
    var numbers = Enumerable.Range(1, 100).ToArray();
    var pickedNumbers = Random.Shared.GetItems(numbers, 3);
}

One piece of advice, though: the GetItems method needs an array or a span to work with, to avoid performance issues. It won't work with IEnumerable.

Two handy methods for ripping off our custom extension methods!