问题
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