0

is it possible to create a List of my own class from a CSV file?

the file e.g. looks like:

ID;NAME
1;Foo
2;Bar

then I have a class like:

class MyClass
{
    public int id { get; set; }
    public string name { get; set; }
}

is it possible to generate a list of this class out of the cvs file? maybe with some library

svick
  • 225,720
  • 49
  • 378
  • 501
gurehbgui
  • 13,218
  • 29
  • 100
  • 167
  • 1
    http://stackoverflow.com/questions/5541503/parsing-a-csv-file-with-c-ignoring-thousand-separators/5541553#5541553 – kenny Feb 24 '13 at 16:07

1 Answers1

4

You could use a CSV parser such as FileHelpers or FastCSV. If you don't want to use third party libraries you may take a look at the built-in TextFieldParser class which could be used like that:

public IEnumerable<MyClass> Parse(string path)
{
    using (TextFieldParser parser = new TextFieldParser(path))
    {
        parser.CommentTokens = new string[] { "#" };
        parser.SetDelimiters(new string[] { ";" });
        parser.HasFieldsEnclosedInQuotes = true;

        // Skip over header line.
        parser.ReadLine();

        while (!parser.EndOfData)
        {
            string[] fields = parser.ReadFields();
            yield return new MyClass()
            {
                id = fields[0],
                name = fields[1]
            };
        }
    }
}

and then:

List<MyClass> list = Parse("data.csv").ToList();

But never, please never roll your own CSV parser as other people suggested you here as answers to your question.

Darin Dimitrov
  • 994,864
  • 265
  • 3,241
  • 2,902
  • never say never. if you know your file structure, maybe writing something small isn't the baddest thing. – gsharp Feb 24 '13 at 16:13
  • You know the file structure. It's CSV :-) `maybe writing something small isn't the baddest thing.`. Quote from here (http://secretgeek.net/csv_trouble.asp): `It's now eight weeks since you said "I know! I'll just use String.Split(..."`. – Darin Dimitrov Feb 24 '13 at 16:14
  • lol okay :) i'm a fan of FileHelpers too. however before FileHelpers was here i splitted and parsed on my own and that stuff still running ;-) – gsharp Feb 24 '13 at 16:23