我正在处理我的第一个真正的 c# 项目,我在基于类创建列表的方式上遇到了问题,我不知道如何解决。
我正在尝试编写一些代码,它采用具有多个层的多个构造的输入文件(txt/csv),将其放入我的程序中,然后将构造写入一个新的 txt/csv 文件。
当具有相同数量的层时,它可以正常工作。但是当结构具有不同数量的层时,它会导致麻烦,我得到一个“System.IndexOutOfRangeException”。我的问题是:我可以使我的列表所基于的类是动态的(我不知道它是否是技术术语),所以它可以处理不同数量的输入吗?将结构添加到程序和将其写入新文件时?
我的代码是:
class Program
{
static void Main(string[] args)
{
// Filepath for the input and output file
string filePathIn_constructions = @"C:\Library\Constructions.txt";
string filePathOut = @"C:\Library\EPlus_Inputfile.txt";
// Creating a list of constructions based on the class. The list is made from the file "filePathIn_constructions"
List<Construction> allConstructions = new List<Construction>();
List<string> lines_constructions = File.ReadAllLines(filePathIn_constructions).ToList(); // add it to a list
// Adding all the data from the fil to the variable "allConstructions"
foreach (var line in lines_constructions)
{
string[] entries = line.Split(',');
Construction newConstruction = new Construction();
newConstruction.EIndex = entries[0];
newConstruction.Name = entries[1];
newConstruction.Layer1 = entries[2];
newConstruction.Layer2 = entries[3];
newConstruction.Layer3 = entries[4];
newConstruction.Layer4 = entries[5];
newConstruction.Layer5 = entries[6];
allConstructions.Add(newConstruction); // Add it to our list of constructions
}
List<string> output = new List<string>();
foreach (var x in allConstructions) // Printing the new
{
output.Add($"{x.EIndex}, {x.Name}, {x.Layer1}, {x.Layer2}, {x.Layer3}, {x.Layer4}, {x.Layer5}");
}
File.WriteAllLines(txtFilePathOut, output);
}
}
我的建筑课是
public class Construction
{
public string EIndex { get; set; }
public string Name { get; set; }
public string Layer1 { get; set; }
public string Layer2 { get; set; }
public string Layer3 { get; set; }
public string Layer4 { get; set; }
public string Layer5 { get; set; }
}
输入/输出文件的示例可能是
Construction,ConcreteWall,Concrete;
Construction,Brickwall1,Birck,Isulation,Brick;
Construction,Brickwall2,Birck,AirGap,Isulation,Brick;
Construction,Wood/Concrete Wall,Wood,Isulation,Concrete,Gypson;
Construction,Wood Wall,Wood,AirGap,Gypson,Isulaiton,Gypson;
我希望有人能帮帮忙。谢谢。
编辑:我必须能够单独超出构造名称,因为我正在使用它来进行一些排序。