Create a List of a given size in C#
原文地址:Create a List of a given size in C# | Techie Delight
This post will discuss how to create a List of a given size in C#. 1. Using List<T> constructor You can use an intermediary array to create an empty list of the specific size. The idea is to create an array with the desired number of items and then convert the array into a list using the List<T> constructor, as shown below: using System; using System.Collections.Generic; public class Example { public static void Main() { int size = 5; List<int> list = new List<int>(new int[size]); Console.WriteLine(String.Join(", ", list)); // 0, 0, 0, 0, 0 } } Download Run Code The above solution initializes a new List<T> containing elements from the specified collection. The List<T> class provides another constructor which takes initial capacity as an argument. The capacity is the number of elements that a List<T> can hold, but does not actually allocate entries in the list. 2. Using Enumerable.Repeat() method Alternatively, you can use LINQ’s Enumerable.Repeat() method to generate a sequence of a repeated value and then convert the sequence into a List with the ToList() method. The following code example initializes a list with specific elements of some value: using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { int size = 5; List<int> list = Enumerable.Repeat(default(int), size).ToList(); Console.WriteLine(String.Join(", ", list)); // 0, 0, 0, 0, 0 } } Download Run Code Alternatively, to add in an existing list, do as follows: using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { int size = 5; List<int> list = new List<int>(size); list.AddRange(Enumerable.Repeat(default(int), size)); Console.WriteLine(String.Join(", ", list)); // 0, 0, 0, 0, 0 } } Download Run Code