Sean Probyn
Sean Probyn

Reputation: 123

How do i sort a text file into number order depending on the last digits?

I've written this code with some help from others which rearranges the last few digits after a > symbol eg.

string[] lines = File.ReadAllLines(SPFile);

var result = lines
  .AsParallel()
  .OrderBy(s => Convert.ToDouble(s.Split('>').Last()))
  .ToList();

File.WriteAllLines(SPFile2, result);

its works fine but now I want to include all the text on the same line and sort in the same way. Here is what it looks like before.

 - 1st Hitman Hearns,Craig Nichol,K Dalgleish,9/2,N/A, >5.5
 - 2nd Discoverie,Henry Brooke,Kenneth Slack,7/2Favourite, >4.5
 - 3rd Aliandy,Thomas Bellamy,K C Bailey,9/2,N/A, >5.5
 - 4th Hear The Chimes,Maurice Linehan,S A Harris,10/1,N/A, >11
 - 5th Kilronan Castle,James Cowley,D Mccain Jnr,16/1,N/A, >17

I need the output file to look like this sorting the last digits smallest first

 - 2nd Discoverie,Henry Brooke,Kenneth Slack,7/2Favourite, >4.5
 - 1st Hitman Hearns,Craig Nichol,K Dalgleish,9/2,N/A, >5.5
 - 3rd Aliandy,Thomas Bellamy,K C Bailey,9/2,N/A, >5.5
 - 4th Hear The Chimes,Maurice Linehan,S A Harris,10/1,N/A, >11
 - 5th Kilronan Castle,James Cowley,D Mccain Jnr,16/1,N/A, >17

How can I do this?

Upvotes: 1

Views: 141

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186823

I suggest using anonymous class:

...
.Select(line => new {
    line = line, // <- what we save (original line)
    order = ...  // <- criterium to sort on 
   })
.OrderBy(item => item.order) // order by criterium
.Select(item => item.line)   // but select original line
...

Implementation:

var result = File
  .ReadLines(SPFile)
  .AsParallel() // if you really want to use PLinq 
  .Select(line => new {
     line = line,
     order = Convert.ToDouble(line.Substring(line.LastIndexOf(">") + 1)) })
  .OrderBy(item => item.order)
  .Select(item => item.line)
  .ToList(); 

File.WriteAllLines(SPFile, result);

Edit: in case

"In some instances there is no number after the >..."

(see the comment below) you can slightly modify the Linq:

using System.Globalization;

...

var result = File
  .ReadLines(SPFile)
  .AsParallel() // if you really want to use PLinq 
  .Select(line => {
     double order;
     bool has = double.TryParse(
       line.Substring(line.LastIndexOf(">") + 1), 
       NumberStyles.Any, 
       CultureInfo.InvariantCulture,
       out order);

     return new {
       line = line,
       order = order,
       has = has   
     };
    })
  .OrderByDescending(item => item.has) // or OrderBy(item => item.has)
  .ThenBy(item => item.order)
  .Select(item => item.line)
  .ToList(); 

Upvotes: 1

fubo
fubo

Reputation: 46005

You have to make sure, the decimal point is converted correctly

var result = lines.AsParallel()
       .OrderBy(s => Convert.ToDouble(s.Split('>').Last(), System.Globalization.CultureInfo.InvariantCulture))
       .ToList();

Upvotes: 1

Related Questions