Search code examples
c#instantiation

Reading CSV file - Object Oriented way


I'd like to parse a csv file in my course that I attend, The cvs file looks like this:

john; 3.5; 32111
etc

I've created a Class for that:

class Student
{
    public string name { get; set; }
    public double average { get; set; }
    public int social_number { get; set; }

    public Student(string name, double average, int social_number)
    {
        this.name = name;
        this.average = average;
        this.social_number = social_number;
    }
    public void CSV_digest(string csv_line)
    {
        if (csv_line != "")
        {
            string[] chunks = csv_line.Split(';');
            name = chunks[0];
            average = Convert.ToDouble(chunks[1]);
            social_number = Convert.ToInt32(chunks[2]);
        }
    }
}

I don't really know how to propagate the Student type array:

class Program
{
    static void Main(string[] args)
    {
        StreamReader csv = new StreamReader("students.csv", Encoding.UTF8);
        string[] csv_lines = csv.ReadToEnd().Split('\n');
        Student[] students = new Student[csv_lines.Length - 1];


        for (int i = 0; i < csv_lines.Length; i++)
        {
           students[i] = 
        }

        Console.ReadKey();
    }
}

Could you please help me with this? I'd really like to utilize classes.


Solution

  • There is really no reason to use a library when the code to read CSV is very simple. See my code below :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            const string filename = @"c:\temp\test.csv";
            static void Main(string[] args)
            {
                StreamReader csv = new StreamReader(filename);
                string line = "";
                List<Student> students = new List<Student>();
                while((line = csv.ReadLine()) != null)
                {
                    students.Add(new Student(line));
                }
    
                Console.ReadKey();
            }
        }
        class Student
        {
            public string name { get; set; }
            public double average { get; set; }
            public int social_number { get; set; }
    
            public Student(string csv_line)
            {
                if (csv_line != "")
                {
                    string[] chunks = csv_line.Split(';');
                    name = chunks[0];
                    average = Convert.ToDouble(chunks[1]);
                    social_number = Convert.ToInt32(chunks[2]);
                }
            }
        }
    }