Home >Backend Development >C++ >How do I efficiently assign values to arrays and lists in C#?
C# Array Value Assignment
Unlike PHP, C# array value assignment requires a specific method. Here's how to populate a C# array:
First, declare the array:
<code class="language-csharp">int[] terms = new int[400];</code>
Then, use a for
loop to assign values to each element:
<code class="language-csharp">for (int runs = 0; runs < 400; runs++) { terms[runs] = runs * 2; // Example: Assigning values }</code>
A More Flexible Approach: Using Lists
C# offers a more dynamic alternative: Lists
. Unlike arrays, lists don't require a predefined size:
<code class="language-csharp">List<int> termsList = new List<int>();</code>
Add values using the Add()
method:
<code class="language-csharp">for (int runs = 0; runs < 400; runs++) { termsList.Add(runs * 2); // Example: Adding values }</code>
To convert the list back to an array, use ToArray()
:
<code class="language-csharp">int[] terms = termsList.ToArray();</code>
Performance Comparison
Consider these performance factors:
for
loops on Lists are roughly twice as fast as foreach
loops.for
loops is approximately twice as fast as List iteration.for
loop on an array is about five times faster than a foreach
loop on a List.The above is the detailed content of How do I efficiently assign values to arrays and lists in C#?. For more information, please follow other related articles on the PHP Chinese website!