This post will discuss how to access a random item in a List<T> in C#.

1. Using Random#Next() Method

A simple and fairly efficient solution to select a random element from a List involves getting a random index value. The idea is to create an instance of the Random class, and generate a random index between 0 and the total number of elements in the List.

The following solution demonstrates this using the Random#Next() method that returns a non-negative random integer that is less than the specified value. In other words, it returns a random number between 0 and specified value minus one (specified value is exclusive).

Download  Run Code

 
You should not create a new instance of the Random class each time a random value is needed. To reuse the same instance of the Random class to uniformly generate random values, you can create an extension method referring to a static field of the Random class:

Download  Run Code

2. Using OrderBy() Method

Another option is to shuffle the whole list using the OrderBy() method and return either the first item or the last item of the list. This works but is very inefficient. However, This can be used if you require multiple random numbers from a list at once.

Download  Run Code

 
You may also use the Fisher-Yates shuffle to shuffle a list in linear time. It does a linear scan of the list and swaps each element with a random element among all remaining elements, including the element itself.

That’s all about accessing a random item in a List<T> in C#.