Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array of string representing numbers (positive and negative as well as having a decimal part)?

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 
like image 384
chapter Avatar asked Jan 13 '21 17:01

chapter


1 Answers

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();
like image 175
Tim Schmelter Avatar answered Nov 03 '22 11:11

Tim Schmelter