简体   繁体   中英

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?

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM