Get Random Element From List in C#

This is a short tutorial on how to get random element from a List in C#.  Basically, this is a console program that demonstrates how the random number generator works and how to use this number as an index to return a random element from a List. This application was compiled in Visual Studio 2022 and .NET 5 as target framework (should compile with .NET 6.0 as well).

Download source code here 

Application Demo

For a quick demo, I’m using .Net Fiddle.  Click the   ► Run   button to see the different results inside the output box. 

Complete Program

Unlike the .NeT Fiddle source code above, the complete program uses a while loop and also uses a Console.ReadKey() command to allow a user to press Escape to exit out of the loop.

// Initialize our list
List<string> mylist = new List<string>(new string[] { "biology-1", "biology-2", "biology-3" });

Random R = new Random();
Console.WriteLine("Press Enter key to continue | Escape key to quit");

ConsoleKeyInfo k = Console.ReadKey();

while (k.Key != ConsoleKey.Escape)
    // get random number from 0 to 2. 
    int someRandomNumber = R.Next(0, mylist.Count);

    Console.WriteLine("Hello {0}", mylist.ElementAt(someRandomNumber));

    k = Console.ReadKey();

Brief Explanation

I created a list of strings initialized with 3 strings, on line #2:

List<string> mylist = new List<string>(new string[] { "biology-1", "biology-2", "biology-3" });

Take note that List<T> requires System.Collections.Generic namespace. To get random element, we use the ElementAt method on line #14:


Take note that ElementAt requires the System.Linq namespace. Like arrays, a list has elements whose position starts at 0 and ends at mylist.Count() - 1. We generate the value for someRandomNumber by using the Random.Next method on line #12:

int someRandomNumber = R.Next(0, mylist.Count());

to get a random number from 0 to mylist.Count()-1. In my example, since I have three elements, I want a random number from 0 to 2. Element #3 does not exist!

And that ends this quick tutorial on getting a random element from a list, and you can use this with different data types too, not just string! Ciao!

Alejandrio Vasay
Alejandrio Vasay

Welcome to Coder Schmoder! I'm a .NET developer with a 15+ years of web and software development experience. I created this blog to impart my knowledge of programming to those who are interested in learning are just beginning in their programming journey.

I live in DFW, Texas and currently working as a .NET /Web Developer. I earned my Master of Computer Science degree from Texas A&M University, College Station, Texas. I hope, someday, to make enough money to travel to my birth country, the Philippines, and teach software development to people who don't have the means to learn it.

Articles: 22

Leave a Reply

Your email address will not be published. Required fields are marked *