选择在ListBox中排序

时间:2015-04-15 16:25:15

标签: c# listbox selection-sort

我想制作一个基于C#的程序,它有来自记事本的输入,其中包含数字,然后将其放在第一个列表框中。然后我有第二个列表框,我想显示第一个列表框中使用SELECTION SORT算法排序的数据。我怎样才能做到这一点? 这是我到目前为止编写的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Sorting
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        static void selectionSort(int[] list, int n)
        {
        int i, j;
        for (i = 0; i < n; i++)
        {
            int min = i;
            for (j = i + 1; j < n; j++)
                if (list[j] < list[min])
                {
                    min = j;
                }
            int temp = list[i];
            list[i] = list[min];
            list[min] = temp;
        }   

    private void btn_open_Click(object sender, EventArgs e)
    {
        string name;
        openFileDialog1.Filter = "Text File (*.txt) | *.txt";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            name = openFileDialog1.FileName;
            listBox1.Items.AddRange(File.ReadAllLines(name));
        }
    }


    private void btn_sort_Click(object sender, EventArgs e)
    {
        int[] list = new int[listBox1.Items.Count];
        for (int a = 0; a < listBox1.Items.Count; a++)
        {
            try
            {
                list[a] = int.Parse(listBox1.Items[a].ToString());
            }

            catch
            {
                DialogResult Text = MessageBox.Show("The data types is not number..", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                break;
            }

            selectionSort(list, listBox1.Items.Count);

        }
        for (int i = 0; i < listBox1.Items.Count-1; i++)
        {
             listBox2.Items.Add(list[i]);
        }                

        }
    }
}

但它没有对排序工作..我的代码有什么问题?

1 个答案:

答案 0 :(得分:0)

如果你想排序:

ListBox lb1 = new ListBox();
ListBox lb2 = new ListBox();
var lb1Items = lb1.Items.Cast<int>().ToList();
lb1Items.Sort();
lb2.DataSource = list;