简体   繁体   中英

How to loop through string array and add each element to object array

Im trying to loop through a string array named string[] splitWords . The array is in the following format:

 // Write your main here
    Write("Enter a number between 1 & 10: ");
    int input = Convert.ToInt32(ReadLine());

    Random ranNumberGenerator = new Random();
    int randomNumber;
    randomNumber = ranNumberGenerator.Next(1, 11);

    if (input == randomNumber)
    {
        WriteLine("correct");
    }
    else if (input < randomNumber)
    {
        WriteLine("too low");
    }
    else
    {
        WriteLine("too high");
    }

Im currently trying to loop through the array which has each element split up individually and assign it to an object array. For example, need to be in their own object array element and so on (every 3 elements). And so in total, there will be 5 elements in the object array. Currently my code is not working, or giving me any errors.

 // Write your main here
        Write("Enter a number between 1 & 10: ");
        int input = Convert.ToInt32(ReadLine());

        Random ranNumberGenerator = new Random();
        int randomNumber;
        randomNumber = ranNumberGenerator.Next(1, 11);

        if (input == randomNumber)
        {
            WriteLine("correct");
        }
        else if (input < randomNumber)
        {
            WriteLine("too low");
        }
        else
        {
            WriteLine("too high");
        }

Using LINQ will make this task very easy:

Station[] stationNames = splitWords
  .Select(word => word.Split(' '))
  .Select(a => new Station(a[0], a[1], a[2]))
  .ToArray();

Your code is close, all you need to do is remove the if block

instead of:

stationNames[stationCounter] = new Station(splitWords[i], splitWords[i + 1], splitWords[i + 2]);
if (stationCounter % 3 == 0)
{
    stationCounter++;
}

You just need:

stationNames[stationCounter] = new Station(splitWords[i], splitWords[i + 1], splitWords[i + 2]);
stationCounter++;

Because each iteration of the loop moves 3 increments so you just need to increment the while counter each time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM