AJC
AJC

Reputation: 13

Creating a List in an if statement and adding onto it in the else

A bit new to Stack + C#, sorry if this question has unfamiliar wording.

I'm trying to create a program that will have an input of plain text separated by lines. If the line is a specific keyword (in this case "group") it'll create a new List. In the else statement, it'll assign the text to the list until the reader reaches another "group".

How could I add to grouping[0] and grouping[1]... etc. through my else statement? The current error I get is "Object reference not set to an instance of an object." I'm assuming I am doing something wrong with the "n" variable, but I'm not sure what.

while ((line = Console.ReadLine()) != null) {

List<String>[] grouping = new List<String>[20];

int count = 0;
int n = 0;

if (line == "group"){
    n++;
    grouping[n] = new List<String>();
}

else {
    grouping[n].Add(line);
}} 

TLDR: What am I doing wrong?

Upvotes: 1

Views: 1182

Answers (1)

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19159

You should move indexer n, and array declaration out of loop, so that values remain after each iteration. also indexes are 0 based in c#. so assign values to array from index 0, not 1.

int n = -1;       
List<string>[] grouping = new List<string>[20];

while ((line = Console.ReadLine()) != null) 
{
    if (line == "group"){
        n++;
        grouping[n] = new List<string>();        
    }
    else 
    {
        grouping[n].Add(line);
    }
} 

Upvotes: 1

Related Questions