如何使用 for 语句更改已数组变量中的名称

本文关键字:变量 数组 for 何使用 语句 | 更新日期: 2023-09-27 18:33:19

我在一个文件夹中有 4 个.txt文档,每个文档有 10 行信息。我想将每个文件中的每一行保存在数组中。我正在寻找一个解决方案,可以给我:

//four arrays with 10 variables each
vFile_0[0-9]
vFile_1[0-9]
vFile_2[0-9]
vFile_3[0-9]

我可以通过在循环中根据 i 命名每个变量来实现这一点:

for (int i = 0; i < vCount; i++)
{
    string[] vFileLine_ + i = File.ReadAllLines("document_" + i + ".txt" );
}

这行不通,有谁知道我要用什么来代替i


编辑:我将进一步详细介绍。我想在一个文件夹中组织任意数量的.txt文档,这些文档内部有随机数量的行。

例:

Document 1 has 6 lines of information.
Document 2 has 3 lines of information.
Document 3 has 12 lines of information.
Document 4 has 5 lines of information.

我希望将所有信息存储到数组中,如果操作正确,变量名称将显示如下:

vFile_0 [5]
vFile_1 [2]
vFile_2 [11]
vFile_3 [4]

正如您在上面看到的,每个文档都有一个各自的变量名称,其数组数量等于该文档中的行,这些数组中的每个变量将该文档中的信息行存储为字符串。这种类型的可变存储的目的是,有一天我可以运行该程序并检测 4 个文件,每个文件有 10 行,或者 120,000 个文件,每个文件有 30,000 行。

我现在遇到的唯一问题是以这种方式命名变量。

如何使用 for 语句更改已数组变量中的名称

您可以将单个vFile_数组替换为双精度数组: string[][] vFile ,按照以下行:

int fileCount = 0; // replace with actual file count...
string [][]vFile = new string[fileCount][];
for (int i = 0; i < fileCount; i++) {
    vFile[i] = File.ReadAllLines("document_" + i + ".txt");
}

你可以使用列表吗?我更喜欢它们而不是数组,尤其是在处理具有可变行数的字符串/文件时。

List<List<String>> allDocuments = new List<List<String>>(); //Note this is a list of lists
for (int i = 0; i < vCount; i++)
{
    string[] tmpRead = File.ReadAllLines("document_" + i + ".txt" );
    List<String> thisDocument = new List<String>();
    foreach(string line in tmpRead) {
        thisDocument.Add(line);
    }
    allDocuments.Add(thisDocument);
}

字典可能是解决您问题的最佳通用选项。您的代码如下所示

Dictionary<string, string[]> fileContents = new Dictionary<string, string[]>(); 
for (int i = 0; i < vCount; i++) 
{     
     fileContents[vFileLine_ + i] = File.ReadAllLines("document_" + i + ".txt" ); 
}

这提供了通用解决方案,可以根据需要添加任意数量的文件的内容。