将 CSV 数据导入 C# 类 [英] Importing CSV data into C# classes

查看:33
本文介绍了将 CSV 数据导入 C# 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何读取和显示 .csv 文件的一行.现在我想解析该文件,将其内容存储在数组中,并将这些数组用作我创建的某些类的值.

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.

不过我想了解一下.

这是一个例子:

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

如您所见,每个字段都用逗号分隔.我创建了 Basketball.cs 和 Baseball 类,它们是 Sport.cs 类的扩展,其中包含以下字段:

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;

我知道这很简单,并且有更好的方法来存储此信息,即为每个团队创建类,使日期成为 DateType 数据类型,等等,但我想知道如何输入此信息信息进入班级.

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.

我假设这与 getter 和 setter 有关...我也读过字典和集合,但我想通过将它们全部存储在数组中来开始简单...(如果这使得感觉......请随时纠正我).

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).

这是我目前所拥有的.它所做的只是读取 csv 并在控制台上鹦鹉学舌:

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

非常感谢您的帮助.

推荐答案

创建数组来保存信息并不是一个好主意,因为您不知道输入文件中有多少行.你的 Array 的初始大小是多少?我建议您使用例如通用列表来保存信息(例如列表<>).

Creating array to keep the information is not a very good idea, as you don't know how many lines will be in the input file. What would be the initial size of your Array ?? I would advise you to use for example a Generic List to keep the information (E.g. List<>).

您还可以向接受数组的运动类添加一个构造函数(上述答案中描述的拆分操作的结果.

You can also add a constructor to your Sport Class that accepts an array (result of the split action as described in above answer.

此外,您可以在 setter 中提供一些转换

Additionally you can provide some conversions in the setters

public class Sport
{
    private string sport;
    private DateTime date;
    private string team1;
    private string team2;
    private string score;

    public Sport(string[] csvArray)
    {
        this.sport = csvArray[0];
        this.team1 = csvArray[2];
        this.team2 = csvArray[3];
        this.date = Convert.ToDateTime(csvArray[1]);
        this.score = String.Format("{0}-{1}", csvArray[4], csvArray[5]);
    }

为了简单起见,我编写了 Convert 方法,但请记住,除非您确定 DateField 始终包含有效日期并且 Score 始终包含数值,否则这也不是一种非常安全的方法.您可以尝试其他更安全的方法,例如 tryParse 或一些异常处理.

Just for simplicity I wrote the Convert Method, but keep in mind this is also not a very safe way unless you are sure that the DateField always contains valid Dates and Score always contains Numeric Values. You can try other safer methods like tryParse or some Exception Handling.

老实说,必须补充一点,上述解决方案很简单(根据要求),从概念上讲,我建议不要这样做.将属性和 csv 文件之间的映射逻辑放在类中会使运动类过于依赖文件本身,从而降低可重用性.文件结构中的任何后续更改都应该反映在您的类中,并且通常会被忽略.因此,将您的映射和主程序中的转换"逻辑,并尽可能保持您的班级干净

I all honesty, it must add that the above solution is simple (as requested), on a conceptual level I would advise against it. Putting the mapping logic between attributes and the csv-file in the class will make the sports-class too dependent on the file itself and thus less reusable. Any later changes in the file structure should then be reflected in your class and can often be overlooked. Therefore it would be wiser to put your "mapping & conversion" logic in the main program and keep your class a clean as possible

(通过将其格式化为 2 个字符串并结合连字符来更改您的分数"问题)

这篇关于将 CSV 数据导入 C# 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆