C# Array Element Adding Method
C# provides multiple methods for creating and adding values to arrays. Unlike PHP, C# arrays require element types and sizes to be specified at creation time. This ensures static memory allocation, thus improving performance.
To create an array that holds 400 integers, use the following syntax:
<code class="language-csharp">int[] terms = new int[400];</code>
After creating an array, you can access and modify its elements using index notation. For example:
<code class="language-csharp">for (int runs = 0; runs < 400; runs++) { terms[runs] = runs * 2; // 为数组元素赋值 }</code>
Alternatively, you can use List<int>
for dynamic element assignment. The list automatically expands as needed, so you don't need to specify a fixed size. However, lists have a slightly higher performance overhead compared to arrays.
<code class="language-csharp">List<int> termsList = new List<int>(); for (int runs = 0; runs < 400; runs++) { termsList.Add(runs * 2); // 向列表添加元素 }</code>
If you need to convert the list back to an array, use the ToArray()
method:
<code class="language-csharp">int[] terms = termsList.ToArray();</code>
Benchmark testing shows that for large data sets, using a for loop to iterate over an array is more efficient than using a foreach loop to iterate over a list.
The above is the detailed content of How to Efficiently Add Elements to Arrays in C#?. For more information, please follow other related articles on the PHP Chinese website!