简体   繁体   中英

C# sorting 2 categories with bubble sort

using System;
using System.IO;

public class Earthquake
{
    public string Magnitude { get; set; }
    public string Location { get; set; }
    public string Latitude { get; set; }
    public string Longitude { get; set; }
    public string depth { get; set; }
    public string date { get; set; }
    public string EventID { get; set; }
    public string URL { get; set; }
    public Earthquake()
        : this(string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty)
    { }
    public Earthquake(string magna, string locate, string lat, string longi, string dept, string dat, string Event, string website)
    {
        Convert.ToDouble(Magnitude = magna);
        Location = locate;
        Convert.ToDouble(Latitude = lat);
        Convert.ToDouble(Longitude= longi);
        Convert.ToDouble(depth = dept);
        date = dat;
        EventID = Event;
        URL = website;
    }

}
public class ManageData
{   
    public void getData()
{
    string[] text = File.ReadAllLines(@"Earthquakes.csv");
    foreach (string line in text)
    {
        string[] myColumns = line.Split(',');
        Earthquake earth = new Earthquake(myColumns[0], myColumns[1], myColumns[2], myColumns[3], myColumns[4], myColumns[5], myColumns[6], myColumns[7]);
        //here i want to put each data in the Earthquake class
    }
}


}

Essentially the csv file is 8 columns, so what I did was read the file by lines, and then create an array that stores each piece of data from a string separated by commas. What I want to do now is sort the data, first by magnitude, and then by depth using bubblesort.

If bubblesort isn't part of the requirement and all you need is a sorted list then you can use LINQ.

Something like this should work.

public class ManageData
{
    public List<Earthquake> AllEarthquakes { get; private set; }
    public IOrderedEnumerable<Earthquake> getData()
    {
        string[] text = File.ReadAllLines(@"Earthquakes.csv");
        foreach (string line in text)
        {
            string[] myColumns = line.Split(',');
            Earthquake earth = new Earthquake(myColumns[0], myColumns[1], myColumns[2], myColumns[3], myColumns[4], myColumns[5], myColumns[6], myColumns[7]);
            //here i want to put each data in the Earthquake class
            AllEarthquakes.Add(earth);
        }

        return AllEarthquakes.OrderBy(eq => eq.Magnitude).ThenBy(eq => eq.depth);
    }
}

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