Random Sampling Of Arrays In C# & .NET
[C#, NET]
A problem you might run to in the course of your application development is that given a array of items, sample a number of elements randomly.
There are two ways we can attempt this:
Random Sorting, Take N Elements
The first (and more inefficient way) is to sort the array randomly, and then pick the desired number of elements from the head of the array.
var numbers = Enumerable.Range(1, 25).ToArray();
var shuffled = numbers.OrderBy(n => Random.Shared.Next())
.Take(10)
.ToArray();
foreach (var number in shuffled)
{
Console.Write($"{number} ");
}
This code will return 10 elements.
2 10 6 18 14 17 22 16 4 19
The drawback of this technique is that it sorts the entire array before sampling. Which can be inefficient if the array is large but you just want to sample a few items.
Random.GetItems Method
A much better way is to make use of the Random.GetItems method that achieves precisely this.
var sampled = Random.Shared.GetItems(numbers, 10);
foreach (var number in sampled)
{
Console.Write($"{number} ");
}
This is much cleaner and terser, and avoids the overhead of sorting the entire array first before selecting the required elements.
This code will return 10 elements.
24 3 22 9 3 10 2 18 15 21
Random.GetItems also works with Spans.
TLDR
The Random.GetItems method can be used to randomly sample elements of an array.
The code is in my GitHub.
Happy hacking!