简体   繁体   中英

sorting csv data by column C#

Hi I have a csv file like

Id Name Age 
1  John 44

I have write code for Altering data and saving as a new file. I need not to alter but to sort that data by Age ascending. Plz help I need it!!! Here is my code.

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());
        }
    }

}

Simply:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM