作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
使用 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/
我是一名优秀的程序员,十分优秀!