Create a List of given size in C#, initialized with some value
This post will discuss how to create a list of a given size in C#, initialized with some value.
We can generate a sequence of a repeated value with LINQ’s Enumerable.Repeat() method. It takes the value to be repeated and the number of times the value has to be repeated in the resulting sequence. The following code example shows an invocation for this method to create a list using the ToList() method:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { int n = 5; List<int> values = Enumerable.Repeat(0, n).ToList(); Console.WriteLine(String.Join(", ", values)); // 0, 0, 0, 0, 0 } } |
The following example demonstrates the usage of the Enumerable.Repeat() method for generating a list of a repeated value with the List constructor.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { int n = 5; List<int> values = new List<int>(Enumerable.Repeat(0, n)); Console.WriteLine(String.Join(", ", values)); // 0, 0, 0, 0, 0 } } |
That’s all about creating a list of a given size in C#, initialized with some value.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)