How to Read text file and Sort list in C#
By FoxLearn 12/1/2024 2:35:23 PM 7.04K
You can use File.ReadAllLines
or File.ReadLines
to read the text file and store its contents into a list or array. After reading the file, you can sort the list using List<T>.Sort()
method.
How to Read text file and Sort list in C#?
Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "ReadTextFileAndSort" and then click OK
Drag and drop the Button, and ListBox controls from the Visual Toolbox onto your form designer, then design your form as shown below.
The method btnOpen_Click
is an event handler for a button click event in a Windows Forms application. When the user clicks the button (presumably labeled "Open"), the btnOpen_Click
method is invoked.
private void btnOpen_Click(object sender, EventArgs e) { using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text Documents(*.txt)|*.txt", ValidateNames = true, Multiselect = false }) { if (ofd.ShowDialog() == DialogResult.OK) { //Read text file string[] lines = System.IO.File.ReadAllLines(ofd.FileName); List<int> list = new List<int>(); foreach (string s in lines) { list.Add(Convert.ToInt32(s)); listReadFile.Items.Add(s); } //Sort list list.Sort(); foreach (int x in list) listSort.Items.Add(x); } } }
The ShowDialog()
method opens the dialog and waits for the user to choose a file. If the user clicks OK, the method proceeds with reading and processing the file.
Once a file is selected, the method uses System.IO.File.ReadAllLines(ofd.FileName)
to read the entire text file into a string array. Each line in the file becomes an individual element in the array.
The next step is to parse the contents of the text file. The method loops through each line, converts it to an integer, and adds it to a List<int>
. This is done using Convert.ToInt32(s)
to ensure the values are treated as integers.
After populating the list, the method sorts the List<int>
in ascending order using the Sort()
method.
Finally, the method loops through the sorted list and adds each item to another ListBox
named listSort
.
VIDEO TUTORIAL
- How to Print Text in a Windows Form Application Using C#
- How to fill ComboBox and DataGridView automatically in C#
- How to pass ListView row data into another Form in C#
- How to read and write to text file in C#
- How to make a Countdown Timer in C#
- How to Display selected Row from DataGridView to TextBox in C#
- How to Get all Forms and Open Form with Form Name in C#
- How to Get Checked Items In a CheckedListBox in C#