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

Viewed 202

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 
3 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();

Array.Sort() is not working because you are trying to sort by string i.e trying to sort lines present in the text file instead of sorting all integers present in that file.

To solve your problem,

  1. You need to read all lines from your file, This step is already done in your code.
  2. Split each line by , then convert all strings into an array of double.
  3. Then Sort it in ascending order.
  4. Now update your richTextBox1

string[] txtDoc = File.ReadAllLines(path);
var sortedList = new List<double>();
foreach(var line in txtDoc)
{
     var value = line.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)
                       .Select(double.Parse)
                       .ToList()
     sortedList.AddRange(value);
}

sortedList.Sort();
richTextBox1.Text = string.Join(Environment.NewLine, sortedList);

if txtDoc is an array that contains all your strings, you may order it this way:

string[] orderedList = 
  txtDoc.OrderBy(x => new string(x.Where(char.IsNumber).ToArray())).ToArray();
Related