我写了一个关于客户注册的程序。客户inf。保存了txt文件。和他们的depts保存访问数据库。我想从小到大排序。我实际上可以对depts进行排序,但是,我想用一些cutome来排序depts。我该怎么办?
private void button2_Click(object sender, EventArgs e)
{
//listBox3.Items.Clear();
OleDbCommand komut = new OleDbCommand();
conn.Open();
OleDbCommand cmd = new OleDbCommand(" SELECT RemainingDept FROM Dept_Tbl ", conn);
OleDbDataReader dr = cmd.ExecuteReader();
List<string> liste = new List<string>();
while ((dr.Read()))
{
liste.Add(dr["RemainingDept"].ToString());
}
string[] A = liste.ToArray();
int[] B;
B = Array.ConvertAll<string, int>(A, int.Parse);
int tmp;
for (int i = 0; i <B.Length ; i++)
{
for (int j=B.Length-1; j>i; j--)
{
if (B[j - 1] > B[j])
{
tmp = B[j - 1];
B[j - 1] = B[j];
B[j] = tmp;
}
}
}
listBox3.Items.Clear();
for (int i = 0; i < B.Length; i++)
{
listBox3.Items.Add( B[i].ToString());
}
conn.Close();
}
}
}
示例:
我的列表框就像这段代码:
30
40
70
我想看到列表框,如:
2 30
1 40
3 70
答案 0 :(得分:0)
将您的查询更改为SELECT ID, RemainingDept FROM Dept_Tbl ORDER BY RemainingDept DESC
。
摆脱排序代码
将读取行更改为:liste.Add(dr["ID"] + " " + dr["RemainingDept"]);
答案 1 :(得分:0)
public class Department
{
public int ID { get; set; }
public int RemainingDept { get; set; }
}
private void button2_Click(object sender, EventArgs e)
{
List<Department> liste = new List<Department>();
OleDbCommand cmd = new OleDbCommand("SELECT ID, RemainingDept FROM Dept_Tbl ORDER BY RemainingDept", conn);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
var dept = new Department()
{
ID = Convert.ToInt32(dr["ID"]),
RemainingDept = Convert.ToInt32(dr["RemainingDept"]);
};
liste.Add(dept);
}
foreach(var nItem in liste)
{
listBox3.Items.Add(nItem.ID + " " + nItem.RemainingDept);
}
}
相同的结果,代码少得多。
private void button2_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand("SELECT ID, RemainingDept FROM Dept_Tbl ORDER BY RemainingDept", conn);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
listBox3.Items.Add(dr["ID"] + " " + dr["RemainingDept"]);
}
答案 2 :(得分:0)
使用它。它将数据排序并将两个字段连接在一起。将其转换为列表,然后显示。跳过自定义排序。
OleDbCommand cmd = new OleDbCommand(" SELECT ID || ' ' || RemainingDept FROM Dept_Tbl ORDER BY RemainingDept", conn);