简体   繁体   中英

List.Add not increasing List.Count

I'm trying to add elements to a List<String> so that I can delete them one at a time from a queue. Here is the code that adds things to my List:

foreach (String s in q)
{
    if(s != null)
    {
        String str = s.Replace("!question", "");
        questions.Add(str);
        this.label1.Text = str;
    }
}

q is an array that I used to split, and questions is a List<String> . Label1 should be irrelevant (I'm using Windows Form)

Here is the code I'm using to try and delete the second line from the list. It throws an 'out of range' exception:

questions.RemoveAt(1);
Console.WriteLine(questions.Count);
foreach(String s in questions)
{
    if (s!= null)
        this.label1.Text = s;
}

When it prints to the console, the Count is one, but if I print the list, it gives me the correct list:

test 1
test 2
test 3 
....

My assumption is that all of my strings are getting added to the list under the first index with return characters, but I'm not quite sure how it works. Thanks everyone!

EDIT : Input .txt:

test 1 \t
test 2 \t
cellosan asks: !question are we getting secret stream? \t
cellosan asks: !question read chat pls \t
cellosan asks: !question sorry for bothering you too \t

EDIT : Full Code

namespace Question_Queue
{
    public partial class Form1 : Form
    {
        public String fullText;
        public String[] questionList;
        public List<String> questions;
        public int i = 0;
        public String[] q;

        public Form1()
        {
            InitializeComponent();
            questionList = new String[20];
            q = new String[30];
            questions = new List<String>(20);

        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }

        //This is the refresh button
        private void button1_Click(object sender, EventArgs e)
        {
            using (FileStream fs = File.Open("C:\\Users\\Lilianne\\Desktop\\questions.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using(StreamReader questionDoc = new StreamReader(fs))
                {
                    //Now we have the stuff in question doc.  Let's make an array for all the questions
                    if (questionDoc.ReadLine() != null)
                    {
                        fullText = questionDoc.ReadToEnd();
                        questionList = fullText.Split('\t');
                        for (int j = 0; j < questionList.Length; j++)
                        {
                            questionList[j] = questionList[j].Replace("!question", "");
                            questionList[j] = questionList[j].Replace("\t", "");
                            this.label1.Text = questionList[j];
                        }

                    }
                    else
                        this.label1.Text = "No questions!";

                    questionDoc.Close();
                }
            }

        }

        private void Answered_Click(object sender, EventArgs e)
        {
            using (FileStream fs = File.Open("C:\\Users\\Lilianne\\Desktop\\questions.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using(StreamReader sr = new StreamReader(fs))
                {
                    //First, remove the topmost question, which is the second line
                    Console.WriteLine(questions.Count);
                    //questions.RemoveAt(2);
                    foreach(String s in questions)
                    {
                        if (s!= null)
                            this.label1.Text = s;
                    }

                }
            }
        }


        private void ClearQueue_Click(object sender, EventArgs e)
        {
            File.WriteAllText("C:\\Users\\Lilianne\\Desktop\\questions.txt", "***** EMPTY LINE *****");
        }

        private void Load_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click_2(object sender, EventArgs e)
        {
            using (FileStream fs = File.Open("C:\\Users\\Lilianne\\Desktop\\questions.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    if (sr.ReadLine() != null)
                    {
                        fullText = sr.ReadToEnd();
                        q = fullText.Split('\t');


                        foreach (String s in q)
                        {
                            if(s != null)
                            {
                                String str = s.Replace("!question", "");
                                questions.Add(str);
                                this.label1.Text = str;
                            }
                        }
                    }
                }
            }
        }
    }
}

I'm assuming that you have two buttons and the first should populate the list with the contents of the file, while the second "Answer" button should be printing the count and removing one item from the list. (I do not see a call to print the contents of the list, and, not knowing where you are making this call, I can't do much to help with that.)

There are a couple of issues that I could see happening here. First, you have two event handlers that could be populating a list based on the contents of the file, namely

private void button1_Click(object sender, EventArgs e)

And

private void button1_Click_2(object sender, EventArgs e)

If you are calling button1_Click before the Answer button is pressed, then this is why you are getting an out of range exception. The handler button1_Click is populating questionList while Answered_Click is reading the data (or lack of) from questions, which has not been populated with any data.

In short, check that your event handlers are mapped correctly.

I would also like to point out that the call to

sr.ReadLine() 

is returning the contents of the first line and moving the stream to the second line. I'm not sure if you are intending to skip the first line and move straight to the second, but simply calling

sr.ReadToEnd()

should suffice.

Furthermore, since the file contains a tab (\\t) at the end of the file, and you are splitting the string on the \\t character, your last record in the array will always be the empty string. This is why

this.label1.Text = s;

does not appear to display any text. It is being fed the empty string.

Edit: Also, that's not the full code. Including the designer code would have been quite handy in identifying the issue.

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