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
235 views
in Technique[技术] by (71.8m points)

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
    }

}

}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


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

...