1

嗨,我有一个 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());
        }
    }

}
4

1 回答 1

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)
于 2013-05-26T21:51:38.683 回答