如何对表示数字的字符串数组(正负以及小数部分)进行排序?

cha*_*ter 5 c# arrays sorting numbers

使用 Windows 表单应用程序,我选择了一个带有随机数值的 txt 文件,我可以将其正确打印在屏幕上。但是当我想对值进行排序时,“Array.Sort (values)”不起作用。我该如何处理?

按钮点击功能

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";
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

输出

10
2
5
-4
12,37
2
69
45
-4,41
35
76
35
-45
6
10
5
4
12
78
25
1
Run Code Online (Sandbox Code Playgroud)

示例txt

10 2 5   -4  

6 10    5    4 12   
35 -45
12,37


2 69 45   -4,41 
35  76
78  25    1 
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 7

您可以使用 LINQ 对数字进行排序并使用以下方法解析它们double.TryParse(您似乎使用逗号作为小数点分隔符):

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();
Run Code Online (Sandbox Code Playgroud)