2

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
  • It's not clear what you are trying to achieve, you are defining a new array with ten elements but then enumerating over all the old elements. Do you want newStringArray to contain the first ten firstnames of oldStringArray? Commented Jun 13, 2015 at 8:18
  • Yes I do want my newStringArray to contain the first ten names of oldStringArray. Commented Jun 13, 2015 at 8:20
  • 2
    You set the whole array, just use the indexer newStringArray[i] = oldStringArray[i].firstName; Commented Jun 13, 2015 at 8:21
  • Change your loop condition from i < oldStringArray.Length to (i < oldStringArray.Length && i < newStringArray.Length) Commented Jun 13, 2015 at 8:26

4 Answers 4

6

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;
    //             ^
}
Sign up to request clarification or add additional context in comments.

1 Comment

If oldStringArray contains more than 10 elements you would then get an index out of bounds exception when accessing newStringArray[10]
3

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();

Comments

2

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;
}

Comments

0

If you want only the first ten firstnames then use

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.