使用QuickSort C#按列对CSV文件进行排序 [英] Sorting CSV file by column using QuickSort c#
问题描述
我有一个名为Item.csv的文件,该文件包含以下信息:
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
我想通过使用QSortAlgorithm按价格对内容进行排序并将其另存为sortedItem.csv. 到目前为止,我可以使用QSortAlgorithm拔出价格列并对其进行排序,但是我不知道如何将它们放在一起.任何帮助将不胜感激.
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]);
推荐答案
您可以使用一个对象将它们组合在一起.我也不知道您的Quicksort算法,但是List类的sort方法似乎做得很好.
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; }
}
但是您应该考虑使用CSV解析器,这是一种更干净的方法.
就像这里描述的TextFieldParser
https://stackoverflow.com/a/20523165/11896942
But you should consider using a CSV parser its a more cleaner approach.
Like the TextFieldParser
described here https://stackoverflow.com/a/20523165/11896942
这篇关于使用QuickSort C#按列对CSV文件进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!