Sorting csv file

后端 未结 1 1043
栀梦
栀梦 2021-01-26 09:20

I have e csv file wich I need to sort. The file looks like:

 ID Name Surname Age Salary
 1  John Asben   33  1000
 2  Adam Smith   22  1200
 3  Amanda J     22  2000
         


        
相关标签:
1条回答
  • 2021-01-26 10:01

    Use Skip to remove the header line for sorting. Use Take + Concat to put the header and the sorted data together again.

    string[] lines = File.ReadAllLines(path);
    var data = lines.Skip(1);
    var sorted = data.Select(line => new
                 {
                    SortKey = Int32.Parse(line.Split(',')[3]),
                    Line = line
                 })
                .OrderBy(x => x.SortKey)
                .Select(x => x.Line);
    File.WriteAllLines(@"C:\Users\sorteddata.csv", lines.Take(1).Concat(sorted));
    
    0 讨论(0)
提交回复
热议问题