Sorting numbers in a csv file.

  • Thread starter Thread starter Francesco2017
  • Start date Start date
F

Francesco2017

Guest
Hi,

I am trying to sort a small csv file that looks like this:

Head1,Head2

A1,23

A2,56

A78,3

B3,78

D1,1

........Using the code below (found online), the sorting places number 3 before number 23.

I understand this is because we are dealing with strings.


So, how can I modify the code below to correct this.

Thank you for your assistance.

regards

Francesco C


static void Main(string[] args)
{
// Create the IEnumerable data source
string[] lines = System.IO.File.ReadAllLines("F:\\sheet1.csv");

// Create the query. Put field 2 first, then
// reverse and combine fields 0 and 1 from the old field
IEnumerable<string> query =from line in lines
let x = line.Split(',')
orderby x[1]
select x[0]+","+(x[1]);

// Execute the query and write out the new file. Note that WriteAllLines
// takes a string[], so ToArray is called on the query.
System.IO.File.WriteAllLines("F:\\sheet2.csv",query.ToArray());

Console.WriteLine("sheet2.csv written to disk. Press any key to exit");
Console.ReadKey();
}

Continue reading...
 
Back
Top