Linq Take Random – Query to Get a Random Sub Collection – Random Order

While writing a load test today, I had to simulate different kind of customers with different kind of taste, and I had a collection of item ids, and to simulate a random distribution, I had to generate a sub collection taking random ids from the collection source, in that way I can simulate different kind of customers that will end-up querying the server requesting different item details.

Googling a little-bit I found an easy way to do this, and is to Order the collection by a different Guid for each row:

var result = collection.OrderBy(t => Guid.NewGuid());

and to get (take) 10 random elements:

var result = collection.OrderBy(t => Guid.NewGuid()).Take(10);

From the Scott Mitchell’s post, you can see some empirical tests that proves a nice random distribution. Of course this is not to use in production code where you absolutely need an unpredictable results, but for load testing, and other take-it-easy purpose, that’s cool.

This is a LINQPad example:

void Main()
{
	var collection = Enumerable.Range(1, 100).ToList();
	
	for (int i = 0; i < 3; i++)
	{
		collection.OrderBy(t => Guid.NewGuid()).Take(10).Dump();
	}
}

linq-take-random

2 thoughts on “Linq Take Random – Query to Get a Random Sub Collection – Random Order”

Leave a comment