With Windows form application, I select a txt file with random numerical values and I can print it on the screen properly. But "Array.Sort (values)" didn't work when I wanted to sort the values. How can I handle this?
Button Click Function
private void button4_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog
{
InitialDirectory = @"C:\",
Title = "Title",
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "txt",
Filter = "txt (*.txt)|*.txt",
FilterIndex = 2,
RestoreDirectory = true,
ReadOnlyChecked = true,
ShowReadOnly = true
};
if(openFileDialog1.ShowDialog()==DialogResult.OK)
{
string path = openFileDialog1.FileName;
string[] txtDoc = File.ReadAllLines(path);
textBox6.Text = path;
Array.Sort(txtDoc);
foreach (string s in txtDoc)
{
txtDoc = s.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
foreach (string ss in txtDoc)
{
richTextBox1.Text +=ss+"\n";
}
}
}
}
OUTPUT
10
2
5
-4
12,37
2
69
45
-4,41
35
76
35
-45
6
10
5
4
12
78
25
1
Sample txt
10 2 5 -4
6 10 5 4 12
35 -45
12,37
2 69 45 -4,41
35 76
78 25 1
You could sort the numbers with LINQ and parse them with double.TryParse
(it seems you use comma as decimal separator):
string[] sortedNumbers = txtDoc
.SelectMany(line => line
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Select(token => double.TryParse(token, out double value) ? value : (double?)null)
.Where(nullableDouble => nullableDouble.HasValue)
.Select(nullableDouble => nullableDouble.Value))
.OrderBy(value => value)
.Select(value => value.ToString())
.ToArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With