Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(de)Serialize from CSV to an object (or preferably a list of type object)

(I am a C++ programmer - trying to learn C# - and it appears that there are some built in object serialization - but I am a bit out of water here...)

I have been asked to load test data into a collection of objects from a CSV file. (CSV is preferred over xml because it is a heck of a lot simpler and readable to humans. We are createing test data to run unit tests)

The collection will be a list of (simple) objects.

List<MyObject>

Where MyObject is a class that contains a few doubles and a few ints.

What is the preferred way to do this? I don't think I will ever have a need to serialize just one of these objects.

I would expect that one single line represents one object, and the set of lines in the file is used to make the list/collection.

like image 952
Tim Avatar asked Jul 14 '11 03:07

Tim


2 Answers

Below should do the trick, just did this a couple months ago for data conversion project i was working on.

A major note to anyone doing CSV (or any character delimited strings), you really should look at using a specific library suited for it. The most popular one I've found is below (pretty tried and true)

You'll start with string.Split(',') and then what do you do when someone accidentally throws a comma in your test data file? ... it's just nightmare after nightmare and this library has traversed most of that for you:

http://www.codeproject.com/KB/database/CsvReader.aspx?msg=3227161

using System.IO;
using LumenWorks.Framework.IO.Csv;

static class Program
{

    public class MyObject
    {
        public int Prop1 { get; set; }
        public string Prop2 { get; set; }
        public decimal Prop3 { get; set; }
    }

    void ReadCsv()
    {
        //holds the property mappings
        Dictionary<string, int> myObjectMap = new Dictionary<string, int>();

        List<MyObject> myObjectList = new List<MyObject>();

        // open the file "data.csv" which is a CSV file with headers
        using (CsvReader csv = new CsvReader(new StreamReader("data.csv"), true))
        {
            int fieldCount = csv.FieldCount;
            string[] headers = csv.GetFieldHeaders();

            for (int i = 0; i < fieldCount; i++)
            {
                myObjectMap[headers[i]] = i; // track the index of each column name
            }

            while (csv.ReadNextRecord())
            {
                MyObject myObj = new MyObject();

                myObj.Prop1 = csv[myObjectMap["Prop1"]];
                myObj.Prop2 = csv[myObjectMap["Prop2"]];
                myObj.Prop3 = csv[myObjectMap["Prop3"]];

                myObjectList.Add(myObj);
            }
        }
    }
}  
like image 124
ericb Avatar answered Sep 23 '22 19:09

ericb


Hate to give out links but this one has the exact sample you're looking for: http://msdn.microsoft.com/en-us/library/bb513866.aspx#Y154

like image 42
Mrchief Avatar answered Sep 25 '22 19:09

Mrchief