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:
mylist.ElementAt(someRandomNumber)
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!