Sorting CSV file by column using QuickSort c#

£可爱£侵袭症+ 提交于 2020-02-16 11:31:13

问题


I have a file called Item.csv file which has the following information:

categoryName, currentPrice, currencyId
Boots, 19.95, GBP
Thermometers,2.03,GBP
Garden Sheds,38.95,GBP

I want to sort the content by price by making use of QSortAlgorithm and save it as sortedItem.csv. So far I can pull out the price column and sort it by making use of QSortAlgorithm but I don't know how to put it all together. Any help would be highly appreciated.

List <double> priceList=new List<double>();
            using (StreamReader sr = new StreamReader("Items.csv"))
            {
                String line;

                while ((line = sr.ReadLine()) != null)
                {
                    string[] parts = line.Split(',');
                    string price = parts[1]; 
                    if(price!="currentPrice")
                    priceList.Add(Convert.ToDouble(price));
                }
            }    
            double [] priceArray=new double[priceList.Count];
             priceArray=priceList.ToArray();
             QuickSort(ref priceArray);
             for(int i=0;i<priceArray.Length;i++)
             Console.WriteLine(priceArray[i]);       

回答1:


You could an object to bring all together. I also do not know your Quicksort algorithm, but the sort method of the List class seems to do a good job.

Here ist your code reworked with an object und sorting all by the price:

List<Item> items = new List<Item>();
using (StreamReader sr = new StreamReader("Items.csv"))
{
    string line;

    while ((line = sr.ReadLine()) != null)
    {
        string[] parts = line.Split(',');
        string price = parts[1];
        if (price != "currentPrice")
            items.Add(new Item
            {
                CurrentPrice = Convert.ToDouble(price),
                CategoryName = parts[0],
                CurrencyId = parts[2]
            });
    }
}
foreach (Item item in items.OrderBy(i => i.CurrentPrice))
    Console.WriteLine(item.CategoryName + "," +
                      item.CurrentPrice + "," +
                      item.CurrencyId);

public class Item
{
    public string CategoryName { get; set; }
    public double CurrentPrice { get; set; }
    public string CurrencyId { get; set; }
}

But you should consider using a CSV parser its a more cleaner approach. Like the TextFieldParser described here https://stackoverflow.com/a/20523165/11896942



来源:https://stackoverflow.com/questions/60016404/sorting-csv-file-by-column-using-quicksort-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!