Remove Item From List<string>


Well-known member
Feb 2, 2013
Programming Experience
I am trying to write some code that fills a label with randomly generated Quotes..I can do this , the problem I am having is removing the item from the list once it is used to fill the code below doesnt work as I thought it would.....

  List<string> message = new List<string>();
            Random rand = new Random(); // initialize the random class
            StreamReader messageReader = new StreamReader("messages.txt");
            string line = "";
            while (line != null)
                line = messageReader.ReadLine();
            for (int i = 0; i < message.Count;  i++)
                int removeMe = rand.Next(0, message.Count);
                lblMessage.Text = message[rand.Next(0, i)];

any help would be appreciated

First of all, if you want to read all the lines from a file then call File.ReadAllLines. Secondly, if you want to loop through a collection and remove items as you go then you need to loop backwards, so that the index of those that you're yet to visit is unaffected by the removal.

There are also some serious flaws in your code. Firstly, you're looping (or at least trying to) through the entire collection in one go. That means that, even if the code works, it's just going to end up displaying the last item selected. I don't see that you want a loop at all. Surely you you just want to pick one item at a time, maybe when the user clicks a button or the like.

I would suggest that you don't even remove anything from the List. File.ReadAllLines returns a string array and you can simply randomise that array and then pick off the items one by one. In that case you'd keep an int to represent the index of the next item to use. Each time you use an item just increment that index. When you get to the end of the list, reset the index to zero and, if desired, re-randomise the array.
var rng = new Random();
var lines = File.ReadAllLines(filePath).OrderBy(s => rng.NextDouble()).ToArray();
Top Bottom