0

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
 4  George Villis 36  2300

My code read data from csv file sorts them and writes to another csv file, but when it reads and writes the data after sorting, it writes just data not the title. Is there any solution to read just data not the title and to write the sorted data With title(ID Name Surnae Age Salary) to another file.

The cole looks like

private void buttonAlterSave_Click(object sender, EventArgs e)
        {
            var sorted =
    File.ReadLines(@"C:\Users\data.csv")
        .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", sorted);
        }

1 Answer 1

5

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));
Sign up to request clarification or add additional context in comments.

2 Comments

Might as well sort it in place using Array.Sort(). Or if a list, List.Sort().
@Tim Schmelter Thank you it was perfect solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.