简体   繁体   English

Java的“ for(String currLine:allLines)”的C#等效项是什么?

[英]What's the C# equivalent of Java's “for (String currLine: allLines)”?

I've got some Java code along the lines of: 我有一些符合以下要求的Java代码:

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#? 用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. 实际上,为澄清起见,我要求的是等同于上述整个代码块,而不仅仅是 for循环。

That would be the foreach construct. 那将是foreach构造。 Basically it is capable to extract an IEnumerable from the supplied argument, and will store all of it's values into the supplied variable. 基本上,它能够从提供的参数中提取IEnumerable ,并将其所有值存储到提供的变量中。

foreach( var curLine in allLines ) {
  ...
}

List<string> can be accessed by index and resizes automatically like Vector. List<string>可以通过索引访问,并且可以像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) { ... }

I guess it's 我想是

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

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

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

It looks like Vector is just a simple list, so this would be the c# equivalent 看起来Vector只是一个简单的列表,所以这将等效于c#

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM