c# - 使用 Array.Sort() 对元素进行排序而不是对第一个元素进行排序

标签 c# arrays sorting

我一直在使用 Array.Sort() 对字符串数组进行排序,但出于某种原因,它保留了数组的第一个元素并且输出不按顺序。

    private void quicksort1_Click(object sender, EventArgs e)
    {


        String[] parts = new String[1000];

        //System.IO.StreamReader file = new System.IO.StreamReader(textBox1.Text);
        System.IO.StreamWriter output = new System.IO.StreamWriter("OUTPUT.txt");

        parts = File.ReadAllLines(textBox1.Text);
        foreach (string s in parts)
        {
                Array.Sort(parts);
                parts.Equals(s);
                output.WriteLine(s);
                counter++;

        }
        output.WriteLine("There were" + " "  + counter + " " + "lines read in.");

        output.Close();

我只是想知道是否有可能解决 Array.Sort() 对第一个元素和其他元素进行排序的位置。

最佳答案

现在,您每行对整个集合进行一次排序。相反,您可以在循环之前对行进行一次排序。

在您当前的代码中,第一行显示未排序,因为您在排序之前获取它:

foreach (string s in parts) // Getting s from the original array
{
   Array.Sort(parts);  //Sorting array
   // s is unchanged - at this point its still the first element from the original array

相反,先排序。试试这个:

private void quicksort1_Click(object sender, EventArgs e)
{
  using (var output = new System.IO.StreamWriter("OUTPUT.txt"))
  {
    string[] parts = File.ReadAllLines(textBox1.Text);
    Array.Sort(parts);
    foreach (string s in parts)
    {
        output.WriteLine(s);
    }

    output.WriteLine("There were {0} lines read in.", parts.Length);
  }

}

请注意,此处也不需要counter 变量,并将代码切换为使用using statement。稍微简化了逻辑。

关于c# - 使用 Array.Sort() 对元素进行排序而不是对第一个元素进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16719642/

相关文章:

c# - 如何让应用程序停止并运行调试器?

php - 合并不同长度的数组

javascript - 如何通过单击主实例中的按钮来显示 2 级子组件的数据?

C# 3.5 分部类 String IsNullOrWhiteSpace

c# - 如何阅读在 asp.net 核心 web api 中发布的 FormUrlEncodedContent?

c# - 迭代 HashSet 时更改项的值

php - 如何通过辅助键获取特定数组元素的值?

ios - 如何按价格对SKProduct数组排序

python - (python) 不使用内置函数存储数据

c++ - 二元归并排序和自然归并排序