简体   繁体   中英

C# reading data from a csv file, with 8 columns, and sorting it

So I am trying to read a csv file that essentially is a list of data separated by words, and I what I have done so far is used ReadAllLines and then from there separated with text.Split(','); The only problem is I just read about this sort of list/array class method rather than creating an actual array, so I have no clue how to call it, or use it. Here is what I have so far:

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
    }

}

}

You may replace

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

with following code lines and see if it helps

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.

当我需要管理 CSV 文件、 C# CSV Reader 和 Writer时,这个项目对我帮助很大

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM