patterncsharpCritical
Adding values to a C# array
Viewed 0 times
valuesaddingarray
Problem
Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example:
For those who have used PHP, here's what I'm trying to do in C#:
int[] terms;
for(int runs = 0; runs < 400; runs++)
{
terms[] = runs;
}For those who have used PHP, here's what I'm trying to do in C#:
$arr = array();
for ($i = 0; $i < 10; $i++) {
$arr[] = $i;
}Solution
You can do this way -
Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.
Edit: a) for loops on List are a bit more than 2 times cheaper than foreach loops on List, b) Looping on array is around 2 times cheaper than looping on List, c) looping on array using for is 5 times cheaper than looping on List using foreach (which most of us do).
int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.
List termsList = new List();
for (int runs = 0; runs < 400; runs++)
{
termsList.Add(value);
}
// You can convert it back to an array if you would like to
int[] terms = termsList.ToArray();Edit: a) for loops on List are a bit more than 2 times cheaper than foreach loops on List, b) Looping on array is around 2 times cheaper than looping on List, c) looping on array using for is 5 times cheaper than looping on List using foreach (which most of us do).
Code Snippets
int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}List<int> termsList = new List<int>();
for (int runs = 0; runs < 400; runs++)
{
termsList.Add(value);
}
// You can convert it back to an array if you would like to
int[] terms = termsList.ToArray();Context
Stack Overflow Q#202813, score: 1065
Revisions (0)
No revisions yet.