Random numbers are crucial in various applications, ranging from simulations and games to cryptography and statistical analysis. In C#, the .NET framework provides a built-in library called System.Random
that allows us to generate random numbers easily.
Let's look at how to populate a list with random integers in C#.
Random
classTo populate a list with random integers in C#, we can use the Random
class to generate random numbers and add them to the list.
using System;using System.Collections.Generic;class Program{static void Main(){List<int> randomNumbers = new List<int>();Random random = new Random();// Generate and add 10 random integers to the listfor (int i = 0; i < 10; i++){int randomNumber = random.Next(); // Generate a random integerrandomNumbers.Add(randomNumber); // Add it to the list}// Print the random numbers in the listforeach (int number in randomNumbers){Console.WriteLine(number);}}}
Let's take a look at the code above:
Line 8: We create an empty list named, randomNumbers
, to store integers.
Line 9: We create an instance of the Random
class named random
to generate random numbers.
Lines 12–16: We use a for
loop to generate 10 random integers and add them to the randomNumbers
list using the Add
method.
Lines 19–22: Finally, we iterate over the list using a foreach
loop and print each random number to the console.
Note: Each time we run the program, we'll get different random numbers because the
Random
class generates pseudo-random numbers based on a seed value. If we want to generate different sequences of random numbers, we can provide a different seed value to theRandom
constructor.
Another way to populate a list with random integers in C# is by using LINQ (Language Integrated Query) and the Enumerable.Range
method, along with the Random
class.
using System;using System.Collections.Generic;using System.Linq;class Program{static void Main(){Random random = new Random();// Generate a list of 10 random integersList<int> randomNumbers = Enumerable.Range(1, 10).Select(x => random.Next()).ToList();// Print the random numbers in the listforeach (int number in randomNumbers){Console.WriteLine(number);}}}
Let's take a look at the code above:
Line 9: We create an instance of the Random
class named random
to generate random numbers.
Line 12-: We use the Enumerable.Range
method to generate a sequence of numbers from 1 to 10.
Line 13: We then use the Select
method to transform each number in the sequence into a random integer generated by the random.Next()
method.
Line 14: Finally, we convert the sequence to a list using the ToList
method and store it in the randomNumbers
variable.
Lines 17–20: We iterate over the list using a foreach
loop and print each random number to the console.
This approach allows us to generate a list of random integers more concisely using LINQ.
Free Resources