How to populate a list with random integers in C#
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#.
Using the Random class
To 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);}}}
Explanation
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
Randomclass namedrandomto generate random numbers.Lines 12–16: We use a
forloop to generate 10 random integers and add them to therandomNumberslist using theAddmethod.Lines 19–22: Finally, we iterate over the list using a
foreachloop and print each random number to the console.
Note: Each time we run the program, we'll get different random numbers because the
Randomclass 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 theRandomconstructor.
Using LINQ
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);}}}
Explanation
Let's take a look at the code above:
Line 9: We create an instance of the
Randomclass namedrandomto generate random numbers.Line 12-: We use the
Enumerable.Rangemethod to generate a sequence of numbers from 1 to 10.Line 13: We then use the
Selectmethod to transform each number in the sequence into a random integer generated by therandom.Next()method.Line 14: Finally, we convert the sequence to a list using the
ToListmethod and store it in therandomNumbersvariable.Lines 17–20: We iterate over the list using a
foreachloop 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