按列排序csv数据
本文关键字:数据 csv 排序 | 更新日期: 2023-09-27 18:15:21
嗨,我有一个csv文件,像
Id Name Age
1 John 44
我已经编写了更改数据和保存为新文件的代码。我不需要修改数据,而是按年龄升序排序。请帮助我,我需要它!这是我的代码。
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());
}
}
}
简体:
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)