I am writing a program which should display the items from an array in a foreach loop.
I wanted to change the elements of the array by adding a string "sad" to each element, but when run the program the array stays the same.
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string[] stringArray = {"hey", "Tom"};
for (int i = 0; i < stringArray.Length; i++ )
{
stringArray[i] += " dad";
Console.WriteLine(stringArray[i]);
}
Array.Resize(ref stringArray, stringArray.Length + 1);
// Add bob to the last element of the array
stringArray[stringArray.Length - 1] =" bob";
foreach (string s in stringArray)
{
string b = s + "sad";
Console.WriteLine(s);
//Console.WriteLine(stringArray);
}
}
}
}
As it turned out, FOREACH is faster on arrays than FOR with length chasing. On list structures, FOREACH is slower than FOR. The code looks better when using FOREACH, and modern processors allow using it. However, if you need to highly optimize your codebase, it is better to use FOR.
“loop through string array c#” Code Answer'sstring[] arr = new string[4]; // Initialize. arr[0] = "one"; // Element 1. arr[1] = "two"; // Element 2. arr[2] = "three"; // Element 3.
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
You can't use it on a string because it's not available on the String prototype.
foreach (string s in stringArray)
{
string b = s + "sad";
// ...
}
Here you are creating a new string, completely unrelated to the string in the string-array. You haven't changed the old string (you can't; strings are immutable). You then simply drop this new longer string on the floor - you aren't updating the array etc.
Try instead something like:
for(int i = 0 ; i < stringArray.Length ; i++)
{
stringArray[i] = stringArray[i] + "sad";
}
This replaces every item in the array with a new string. Note that you can't update a list/collection/array etc while iterating with foreach
- that can break the iterator. Hence the for
loop instead.
Apart from what Chris said, you could simply use LINQ to achieve what you want:
string[] newStringArray = stringArray
.Select(s => s + "sad")
.ToArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With