Sean Probyn
Sean Probyn

Reputation: 123

How can i put a text file in numerical order based on what it starts with?

Here is an example of the text file...

7</DOdds>Some Text Here
4.5</DOdds>Some Text Here 
11</DOdds>Some Text Here
8.5</DOdds>Some Text Here

...Im trying to get the output file like this...

4.5</DOdds>Some Text Here
7</DOdds>Some Text Here
8.5</DOdds>Some Text Here
11</DOdds>Some Text Here

heres my code...

                foreach (var line in File.ReadLines(myfile))
                {
                    string[] lines = File.ReadAllLines(line);
                    var result = lines.AsParallel().OrderBy(s => s.Split('<').First()).ToList();
                    File.WriteAllLines(line, lines);
                

Can someone point me in the right direction please?

Upvotes: 3

Views: 95

Answers (2)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48327

You should convert to double the first element after splitting the string.

var lines = File.ReadAllLines(myfile);
var result = lines.AsParallel().OrderBy(s => Convert.ToDouble(s.Split('<').First())).ToList();
File.WriteAllLines(myfile, result);

Output

4.5</DOdds>Some Text Here 
7</DOdds>Some Text Here
8.5</DOdds>Some Text Here
11</DOdds>Some Text Here

Upvotes: 1

Thomas Koelle
Thomas Koelle

Reputation: 3742

I haven't tested it, but would assume you can just add this to you code:

Convert.ToDouble()

Ie.

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

Upvotes: 0

Related Questions