gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:53:50 25 4
gpt4 key购买 nike

使用 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";
}
}
}
}
输出
10
2
5
-4
12,37
2
69
45
-4,41
35
76
35
-45
6
10
5
4
12
78
25
1
示例txt
10 2 5   -4  

6 10 5 4 12
35 -45
12,37


2 69 45 -4,41
35 76
78 25 1

最佳答案

您可以使用 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();

关于c# - 如何对表示数字的字符串数组(正负以及小数部分)进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65707327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com