开发者

Order the lines in a file by the last character on the line

Can you please help me with this: I want to build a method in C# which will order a lot of files by the following rule开发者_运维百科 every line contains strings and the last character in every line is an int. I want to order the lines in the file by this last character, the int.

Thanks


To order ascending by the last character, interpreted as an integer you could do:

var orderedLines= File.ReadAllLines(@"test.txt")
                        .OrderBy(line => Convert.ToInt32(line[line.Length-1]))
                        .ToList();

Edit:

With the clarification in your comment - integer following a space character, can be more than one digit:

var orderedLines= File.ReadAllLines(@"test.txt")
                      .OrderBy(line => Convert.ToInt32(line.Substring(line.LastIndexOf(" ")+1, 
                                                                        line.Length - line.LastIndexOf(" ")-1)))
                      .ToList();


You could do something like this, where filename is the name of your file:

// Replace with the actual name of your file
string fileName = "MyFile.txt";

// Read the contents of the file into memory 
string[] lines = File.ReadAllLines(fileName);

// Sort the contents of the file based on the number after the last space in each line
var orderedLines = lines.OrderBy(x => Int32.Parse(x.Substring(x.LastIndexOf(' '))));

// Write the lines back to the file
File.WriteAllText(fileName, string.Join(Environment.NewLine, orderedLines));

This is just a rough outline; hopefully it's helpful.


File.WriteAllLines(
    pathToWriteTo,
    File.ReadLines(pathToReadFrom)
        .OrderBy(s => Convert.ToInt32(s.Split(' ').Last()))
);

If the file is large, this could be ineffective as this method of sorting effectively requires reading the entire file into memory.


Assuming you want more than single digit integers and that you have a separation character between the filename and the rest (we'll call it 'splitChar') which can be any character at all:

from string str in File.ReadAllLines(fileName) 
    let split = str.Split(splitChar)
    orderby Int32.Parse(split[split.Count()-1]) 
    select str

will get you a sequence of strings in order of the integer value of the last grouping (separated by the split character).


Maybe one of these links can help you by sorting it the natural way:

  • Natural Sorting in C#
  • Sorting for Humans : Natural Sort Order
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜