Reputation: 57
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);
}
Upvotes: 0
Views: 10630
Reputation: 460108
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));
Upvotes: 5