读取CSV文件-面向对象的方式

时间:2019-07-14 17:46:40

标签: c# instantiation

我想在我参加的课程中解析一个csv文件,该cvs文件如下所示:

john; 3.5; 32111
etc

我为此创建了一个类:

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

我真的不知道如何传播学生型数组:

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

您能帮我吗?我真的很想利用类。

1 个答案:

答案 0 :(得分:-3)

当读取CSV的代码非常简单时,实际上没有理由使用库。请参阅下面的代码:

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