5

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 
chapter
  • 53
  • 2
  • 1
    Does this answer your question? [Array.Sort for strings with numbers](https://stackoverflow.com/questions/22796494/array-sort-for-strings-with-numbers) and [How to sort a string array by numeric style?](https://stackoverflow.com/questions/6723487/how-to-sort-a-string-array-by-numeric-style) –  Jan 13 '21 at 18:00
  • Your sort is not going to be numeric, as you're performing it on an array of strings, not an array of numbers. – Robert Harvey Jan 13 '21 at 18:00
  • Why do you have a plus sign at the end? richTextBox1.Text +=ss+ – jdweng Jan 13 '21 at 18:01
  • Also, your array doesn't represent the actual output you want. To get that, you're going to have to do the `Split` thing on the array first, and then perform your sort. – Robert Harvey Jan 13 '21 at 18:02
  • @jdweng: They're concatenating a newline. – Robert Harvey Jan 13 '21 at 18:02
  • Yes, I guess each line is a separate index. How can I separate each number? @TimSchmelter – chapter Jan 13 '21 at 18:04

3 Answers3

7

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();
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Thank you for help. But I updated it like this because it gave an error in line 3. `Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)` – chapter Jan 13 '21 at 18:23
  • @chapter: ok, that works too, but you have noticed that i was using a `char` not a `string` as first parameter? That overload of `String.Split` exists: https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=net-5.0#System_String_Split_System_Char_System_StringSplitOptions_ – Tim Schmelter Jan 13 '21 at 18:27
1

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);
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
  • Thank you for the help. Your code works fine but I guess you should write foreach instead of for :) – chapter Jan 13 '21 at 18:27
0

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();
Max Alexander Hanna
  • 3,388
  • 1
  • 25
  • 35