1

How can I create a csv file from a generic list of objects? In the example, a list of molecules, containing 3 objects of the type 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);

Here, one can print the content of one of the properties of the list for the 3 objects:

            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();
        }
    }
}

The output:

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

So I need a csv file with the complete output:

10,20
3,7
13,13.5

I tried to find such method in the forums, but I only found examples for generic lists of arrays, and I was not able to make them work. I really appreciate any help on this issue (I'm a beginner in C#).

  • https://stackoverflow.com/questions/1890093/converting-a-generic-list-to-a-csv-string – Gustavo Oliveira May 14 '20 at 23:16
  • @GustavoOliveira this example refers to a list of strings. In my case the list contain objects, which have themselves two different properties each. The csv should contain these properties listed per molecule. – Antonio Intini May 14 '20 at 23:20
  • Does this answer your question? [Fastest way to convert a list of objects to csv with each object values in a new line](https://stackoverflow.com/questions/25683161/fastest-way-to-convert-a-list-of-objects-to-csv-with-each-object-values-in-a-new) – Jim G. Mar 16 '23 at 15:10

2 Answers2

5

CSV files are pretty straight forward to generate:

using (StreamWriter writer = new StreamWriter("myfile.csv"))
{
    foreach (Molecule molecule in molecules)
    {
        writer.WriteLine($"{molecule.property_A},{molecule.property_B}");
    }
}
itsme86
  • 19,266
  • 4
  • 41
  • 57
  • Thanks for your reply! I'm getting an error: "The type or namespace 'StreamWriter' could not be found (are you missing a using directive or an assembly reference?)". Any guess of what should I do next? – Antonio Intini May 14 '20 at 23:26
  • 1
    I found a correction for this: using (System.IO.StreamWriter writer = new System.IO.StreamWriter(@"myfile.csv")) Now it is working perfectly. Thank you so much! – Antonio Intini May 14 '20 at 23:42
1

Have you tried System.IO.File yet? It's a simple way of opening and writing to a file: example.

It looks like you'll need some sort of method like the following;

    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));
            }
        }
    }
BaconSodas
  • 74
  • 3
  • I was not able to run it. Molecule is not an array. I get the error: "Argument 2: cannot convert from 'System.Collections.Generic.List' to 'example_reactioncalc.Program.Molecule[]' – Antonio Intini May 14 '20 at 23:37
  • Here, try the edit instead. Should accept a List instead of an Array now – BaconSodas May 14 '20 at 23:43