Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
784 views
in Technique[技术] by (71.8m points)

class - Importing CSV data into C# classes

I know how to read and display a line of a .csv file. Now I would like to parse that file, store its contents in arrays, and use those arrays as values for some classes I created.

I'd like to learn how though.

Here is an example:

basketball,2011/01/28,Rockets,Blazers,98,99
baseball,2011/08/22,Yankees,Redsox,4,3

As you can see, each field is separated by commas. I've created the Basketball.cs and Baseball classes which is an extension of the Sport.cs class, which has the fields:

private string sport;
private string date;
private string team1;
private string team2;
private string score;

I understand that this is simplistic, and that there's better ways of storing this info, i.e. creating classes for each team, making the date a DateType datatype, and more of the same but I'd like to know how to input this information into the classes.

I'm assuming this has something to do with getters and setters... I've also read of dictionaries and collections, but I'd like to start simple by storing them all in arrays... (If that makes sense... Feel free to correct me).

Here is what I have so far. All it does is read the csv and parrot out its contents on the Console:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Assign01
{
    class Program
    {
        static void Main(string[] args)
        {
            string line;
            FileStream aFile = new FileStream("../../sportsResults.csv", FileMode.Open);
            StreamReader sr = new StreamReader(aFile);

            // read data in line by line
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line);
                line = sr.ReadLine();
            }
            sr.Close();
        }
    }
}

Help would be much appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For a resilient, fast, and low effort solution, you can use CsvHelper which handles a lot of code and edge cases and has pretty good documentation

First, install the CsvHelper package on Nuget

CsvHelper nuget download

a) CSV with Headers

If your csv has headers like this:

sport,date,team 1,team 2,score 1,score 2
basketball,2011/01/28,Rockets,Blazers,98,99
baseball,2011/08/22,Yankees,Redsox,4,3

You can add attributes to your class to map the field names to your class names like this:

public class SportStats
{
    [Name("sport")]
    public string Sport { get; set; }
    [Name("date")]
    public DateTime Date { get; set; }
    [Name("team 1")]
    public string TeamOne { get; set; }
    [Name("team 2")]
    public string TeamTwo { get; set; }
    [Name("score 1")]
    public int ScoreOne { get; set; }
    [Name("score 2")]
    public int ScoreTwo { get; set; }
}

And then invoke like this:

List<SportStats> records;

using (var reader = new StreamReader(@".stats.csv"))
using (var csv = new CsvReader(reader))
{
    records = csv.GetRecords<SportStats>().ToList();
}

b) CSV without Headers

If your csv doesn't have headers like this:

basketball,2011/01/28,Rockets,Blazers,98,99
baseball,2011/08/22,Yankees,Redsox,4,3

You can add attributes to your class and map to the CSV ordinally by position like this:

public class SportStats
{
    [Index(0)]
    public string Sport { get; set; }
    [Index(1)]
    public DateTime Date { get; set; }
    [Index(2)]
    public string TeamOne { get; set; }
    [Index(3)]
    public string TeamTwo { get; set; }
    [Index(4)]
    public int ScoreOne { get; set; }
    [Index(5)]
    public int ScoreTwo { get; set; }
}

And then invoke like this:

List<SportStats> records;

using (var reader = new StreamReader(@".stats.csv"))
using (var csv = new CsvReader(reader))
{
    csv.Configuration.HasHeaderRecord = false;
    records = csv.GetRecords<SportStats>().ToList();
}

Further Reading


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...