您好我有一个像
这样的csv文件Id Name Age
1 John 44
我已经编写了修改数据和保存为新文件的代码。我不需要改变,而是按Age提升对数据进行排序。 Plz帮助我需要它! 这是我的代码。
private void buttonAlterSave_Click(object sender, EventArgs e)
{
List<string[]> parsedData = ReadAndtParsedata(@"C:....data.csv", ',');
foreach (string[] row in parsedData)
{
if (row != parsedData[0])
{
string name = (row[1].Replace("\"", ""));
string[] temp = name.Split();
var sb = new StringBuilder(temp.LastOrDefault());
sb.Append(',');
for (int i = 0; i < temp.Length - 1; i++)
{
sb.Append(" ");
sb.Append(temp[i]);
}
sb.Insert(0, "\"");
sb.Append("\"");
row[1] = sb.ToString();
}
}
using (var sw = new StreamWriter(@"C:....altereddata.csv"))
{
foreach (string[] row in parsedData)
{
var sb = new StringBuilder();
foreach (string s in row)
{
sb.Append(s + ";");
}
sb.Remove(sb.Length - 1, 1);
sw.WriteLine(sb.ToString());
}
}
}
答案 0 :(得分:0)
简单地:
var sorted =
File.ReadLines(inputPath)
.Select(line => new {
SortKey = Int32.Parse(line.Split(',')[2]),
Line = line
})
.OrderBy(x => x.SortKey)
.Select(x => x.Line);
File.WriteAllLines(outputPath, sorted)