如何从通用对象列表创建csv文件?在该示例中,一个分子列表,其中包含3个类型为Molecule的对象:
namespace example_reactioncalc
{
class Program
{
public class Molecule
{
public double property_A { get; set; }
public double property_B { get; set; }
}
public static Molecule Reaction(Molecule molecule_1, Molecule molecule_2)
{
Molecule reacted_molecule = new Molecule();
reacted_molecule.property_A = molecule_1.property_A + molecule_2.property_A;
reacted_molecule.property_B = (molecule_1.property_B + molecule_2.property_B) / 2;
return reacted_molecule;
}
static void Main(string[] args)
{
// Initiation of the list of molecules
List<Molecule> molecules = new List<Molecule>();
// Adding two molecules to the list
molecules.Add(new Molecule() { property_A = 10, property_B = 20 });
molecules.Add(new Molecule() { property_A = 3, property_B = 7 });
// Reacting two molecules to get a new one:
Molecule new_molecule=Reaction(molecules[0],molecules[1]);
molecules.Add(new_molecule);在这里,用户可以打印3个对象的列表属性之一的内容:
Console.WriteLine("Properties A and B of the 1st molecule:");
Console.WriteLine(molecules[0].property_A);
Console.WriteLine(molecules[0].property_B);
Console.WriteLine("Property A and B of the 2nd molecule:");
Console.WriteLine(molecules[1].property_A);
Console.WriteLine(molecules[1].property_B);
Console.WriteLine("Property A and B of the 3rd, new molecule:");
Console.WriteLine(molecules[2].property_A);
Console.WriteLine(molecules[2].property_B);
Console.ReadLine();
}
}
}输出:
Properties A and B of the 1st molecule:
10
20
Properties A and B of the 2nd molecule:
3
7
Properties A and B of the 3rd, new molecule:
13
13.5因此,我需要一个包含完整输出的csv文件:
10,20
3,7
13,13.5我试图在论坛中找到这样的方法,但我只找到了数组的泛型列表的示例,并且我无法使它们工作。我真的很感谢在这个问题上的任何帮助(我是C#的初学者)。
发布于 2020-05-15 07:19:02
CSV文件很容易生成:
using (StreamWriter writer = new StreamWriter("myfile.csv"))
{
foreach (Molecule molecule in molecules)
{
writer.WriteLine($"{molecule.property_A},{molecule.property_B}");
}
}发布于 2020-05-15 07:26:41
你试过System.IO.File了吗?这是一种简单的打开和写入文件的方法:example。
看起来你需要像下面这样的方法;
WriteMoleculesToFile(string pathToFile, List<Molecule> molecules) {
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@pathToFile)) {
foreach (Molecule molecule in molecules) {
file.WriteLine(String.Format("{0},{1}",molecule.property_A, molecule.property_B));
}
}
}https://stackoverflow.com/questions/61808901
复制相似问题