0

First I'm a very Beginner in c#, and Sorry for my english I'm trying to sort myfile:"D:\Test.txt" by the number sfter the first "|"

FROM :
AVDT353|180 |||14/01/2021||
GSDF445|10 |||14/01/2021||
MLKLMK6|17023 |||14/01/2021||

TO :
GSDF445|10 |||14/01/2021||
AVDT353|180 |||14/01/2021||
MLKLMK6|17023 |||14/01/2021||

2 Answers 2

2

First, load the text file. Then, create a list of strings by using line breaks as the delimiter. Next, sort the lines using Linq, splitting after the | character. Finally, write the strings to file, putting each on a new line.

string contents = File.ReadAllText(@"D:\Test.tx");
var lines = contents.Split(Environment.NewLine).ToList();
var sorted = lines.OrderBy(l => l.Split("|")[1]).ToList();
// To update the content of the file:
File.WriteAllText(@"D:\Out.tx", string.Join(Environment.NewLine, sorted));
Sign up to request clarification or add additional context in comments.

3 Comments

Wouldn't you need to do some kind of string-to-int conversion?
@RoyCohen we can sort strings lexicographically without converting to integers, conversion to int is unnecessary.
@AbdiBarid I've updated my answer to include writing to an output file.
0
  void SortFile()
        {
            DirectoryInfo d = new DirectoryInfo(@"D:\Test");//Assuming Test is your Folder
            FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
            string str = "";
            foreach (FileInfo file in Files)
            {
                int fileNo = Convert.ToInt32(file.Name.Split('|')[1]);
                for (int i = 0; i < Files.Length; i++)
                {
                    if (fileNo < Convert.ToInt32((Files[i].Name.Split('|')[1])))
                    {
                        //Add it to list or something
                    }
                }
            }
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.