-1

所以我试图读取一个 csv 文件,它本质上是一个由单词分隔的数据列表,而我到目前为止所做的是使用 ReadAllLines ,然后从那里用 text.Split(','); 分隔。唯一的问题是我只是阅读了这种列表/数组类方法,而不是创建一个实际的数组,所以我不知道如何调用它或使用它。这是我到目前为止所拥有的:

using System;
using System.IO;
public class Earthquake
{
    public double Magnitude { get; set; }
    public string Location { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public double depth { get; set; }
    public string date { get; set; }
    public string EventID { get; set; }
    public string URL { get; set; }
    public Earthquake(double magna, string locate, double lat, double longi, double dept, string dat, string Event, string website)
    {
        Magnitude = magna;
        Location = locate;
        Latitude = lat;
        Longitude= longi;
        depth = dept;
        date = dat;
        EventID = Event;
        URL = website;
    }

}
public class ManageData
{

    public int count;
    public void getData()
{
    string[] text = File.ReadAllLines(@"Earthquakes.csv");
    foreach (string word in text[count].Split(','))
    {
        //here i want to put each data in the Earthquake class
    }

}

}
4

2 回答 2

0

你可以更换

foreach (string word in text[count].Split(','))
    {
        //here i want to put each data in the Earthquake class
    }

使用以下代码行,看看它是否有帮助

foreach (string line in text)
{
  string[] myColumns = line.Split(',');

  EarthQuake eQ = new EarthQuake(myColumns[0],myColumns[1],myColumns[2],myColumns[3],myColumns[4],myColumns[5],myColumns[6],myColumns[7],myColumns[8]);
  //Add eQ into a list you want to save

}

This assumes the columns are in same order. If the order is different than rather than using this constructor, use default constructor and then assign values to the properties of EarthQuake class accordingly.

Hope that helps.

于 2012-11-27T05:43:36.230 回答
0

This Project helped me a lot when I needed to manage CSV files, C# CSV Reader and Writer

于 2012-11-27T05:55:20.567 回答