How do I store an array of strings into another array of strings?

4.7k Views Asked by At

I'm trying to store my old array of struct type that holds first names of people into a new string array that has been downsized so I can then shuffle it round in another method.

string[] newStringArray = new string[10]

for (int i = 0; i < oldStringArray.Length; i++)
{    
    newStringArray = oldStringArray[i].firstName;//Cannot convert type 'string to 'string[]'
}

foreach (string value in newStringArray)
{
    Console.WriteLine(value);
}
4

There are 4 best solutions below

1
On BEST ANSWER

It looks like you forgot the index accessor:

string[] newStringArray = new string[10];
for (int i = 0; i < oldStringArray.Length && i < newStringArray.Length; i++)
{
    newStringArray[i] = oldStringArray[i].firstName;
    //             ^
}
0
On

You can project your FirstName properties using Enumerable.Select, and then materialize them into a new array using Enumerable.ToArray:

string[] firstNames = oldStringArray.Select(x => x.FirstName).ToArray();
0
On

If you want only the first ten firstnames then use

var firstTenFirstNames = oldStringArray.Select(x => x.FirstName).Take(10).ToArray()
0
On

You have to declare the new array with the same size as the old one.

string[] newStringArray = new string[oldStringArray.Length];

Then use the indexer to set the elements of the new array.

for (int i = 0; i < oldStringArray.Length; i++)
{    
    newStringArray[i] = oldStringArray[i].firstName;
}