How do I take each element off of a list and push it onto a stack?

Viewed 89
string filePath = @"C:\Users\Me\Desktop\Palindromes\palindromes.txt";

List<string> lines = File.ReadAllLines(filePath).ToList();
var meStack = new Stack<string>();

for (int i = 0; i < lines.Count; i++)
{
    string pali;
    pali = lines.RemoveAt(i);
    meStack.Push(pali[i]);
}

Basically I need to Remove each element (in the txt there are 40 lines) from the list and then Push each one onto a stack.

4 Answers

Why even make a list List<String>? ReadAllLines responds with a String[]. And Stack takes an array as constructor parameter... So, would code below do the job for you?

  string filePath = @"C:\Users\Me\Desktop\Palindromes\palindromes.txt";
  var meStack = new Stack<string>(File.ReadAllLines(filePath));

Do not RemoveAt but Clear (if necessary) the lines list at the very end:

  for (int i = 0; i < lines.Count; ++i)
    meStack.Push(lines[i]);

  lines.Clear();

Or even (we can get rid of list at all):

  string filePath = @"C:\Users\Me\Desktop\Palindromes\palindromes.txt";

  var meStack = new Stack<string>(); 

  foreach (var item in File.ReadLines(filePath))
    meStack.Push(item);

You can simplify it to

lines.ForEach(meStack.Push);
lines.Clear();

Your code with some comments:

string filePath = @"C:\Users\Me\Desktop\Palindromes\palindromes.txt";
List<string> lines = File.ReadAllLines(filePath).ToList();
var meStack = new Stack<string>();

for (int i = 0; i < lines.Count; i++)
{
   string pali;
   pali = lines.RemoveAt(i); // < this will return AND REMOVE the line from the list.
                             // now, what was line i+1 is now line i, next iteration
                             // will return and remove (the new) line i+1, though,
                             // skipping one line.
   meStack.Push(pali[i]);    // here you push one char (the ith) of the string (the line you  
                             // just removed) to the stack which _may_ cause an 
                             // IndexOutOfBounds! (if "i" >= pali.Length )
}

Now since I do not want to reiterate the other (great) answers, here is one where you can actually use RemoveAt:

while( lines.Count > 0 ) // RemoveAt will decrease Count with each iteration
{
    meStack.Push(lines.RemoveAt(0)); // Push the whole line that is returned.
    // Mind there is hardcoded "0" -> we always remove and push the first
    // item of the list.
}

Which is not the best solution, just another alternative.

Related