views:

109

answers:

6

I've got some Java code along the lines of:

Vector<String> allLines = new Vector<String>();
allLines.add("line 1");
allLines.add("line 2");
allLines.add("line 3");
for (String currLine: allLines) { ... }

Basically, it reads a big file into a lines vector then processes it one at a time (I bring it all in to memory since I'm doing a multi-pass compiler).

What's the equivalent way of doing this with C#? I'm assuming here I won't need to revert to using an index variable.


Actually, to clarify, I'm asking for the equivalent of the whole code block above, not just the for loop.

+6  A: 

That would be the foreach construct. Basically it is capable to extract an IEnumerable from the supplied argument, and will store all of it's values into the supplied variable.

foreach( var curLine in allLines ) {
  ...
}
xtofl
A: 

foreach(string currLine in allLines) { ... }

Matt Greer
+1  A: 

I guess it's

foreach (string currLine in allLines)
{
   ...
}
Graham Clark
+5  A: 

List<string> can be accessed by index and resizes automatically like Vector.

So:

List<string> allLines = new List<string>();
allLines.Add("line 1");
allLines.Add("line 2");
allLines.Add("line 3");
foreach (string currLine in allLines) { ... }
Nick Miller
A: 
List<string> allLines = new List<string>
{
    "line 1",
    "line 2",
    "line 3",
};
foreach (string currLine in allLines) { ... } 
Gabe
A: 

It looks like Vector is just a simple list, so this would be the c# equivalent

List<string> allLines = new List<string>();
allLines.add("line 1");
allLines.add("line 2");
allLines.add("line 3");
foreach (string currLine in allLines) { ... }
Haas