Khushi
Khushi

Reputation: 1051

how to add ith item from one List to another

Suppose I have 2 lists:

List<string> CharactersInStringEnteredByUser = new List<string>();
List<string> CharactersInAutomaticallyGeneratedString = new List<string>();

while (CharactersInStringEnteredByUser.Count < 25)
{
    CharactersInStringEnteredByUser.Add(????);
}

I want to add ith item from CharactersInAutomaticallyGeneratedString to CharactersInStringEnteredByUser.

*Update: *

Let me clarify my question.

I want to check if CharactersInStringEnteredByUser < 25 ? If so then add first item from CharactersInAutomaticallyGeneratedString.

Now again check if CharactersInStringEnteredByUser < 25 ? If so then add second item from CharactersInAutomaticallyGeneratedString.

And so on......

Upvotes: 0

Views: 82

Answers (2)

Sachin
Sachin

Reputation: 40990

Probably you want to take first 25 values from first list and save them into second. So you can do this

CharactersInStringEnteredByUser = CharactersInAutomaticallyGeneratedString.Take(25).ToList();

If your list may be already filled (as you are checking its count) then you can do this.

int count = CharactersInStringEnteredByUser.Count;
if(count < 25)
  CharactersInStringEnteredByUser = CharactersInAutomaticallyGeneratedString.Take(25-count).ToList();

Upvotes: 2

Liel
Liel

Reputation: 2437

List<string> CharactersInStringEnteredByUser = new List<string>();
List<string> CharactersInAutomaticallyGeneratedString = new List<string>();

int i = 0;
while (CharactersInStringEnteredByUser.Count < 25)
{
    CharactersInStringEnteredByUser.Add(CharactersInAutomaticallyGeneratedString[i]);
    i++;
}

You should also verify that CharactersInAutomaticallyGeneratedString has enough items. I would add a check in the loop's body.

The final code can be:

int i = 0;
while (CharactersInStringEnteredByUser.Count < 25)
{
    if (i >= CharactersInAutomaticallyGeneratedString.Count)
        break;

    CharactersInStringEnteredByUser.Add(CharactersInAutomaticallyGeneratedString[i]);
    i++;
}

Upvotes: 0

Related Questions