需求:可以给label赋值,然后通过这个赋值去对label排序。给label赋的值不在label上显示。
原理:利用字典去结合我们的百分比数,然后通过字典去排序。排序完毕之后,我们通过按照排序过的后的序列去给Label重写位置信息。这里一定要注意重写位置,否则再怎么排序都是原来初始化时的位置。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
arrayLabel();
}
private void arrayLabel()
{
Label[] labels = new Label[5];
List<Label> la = new List<Label>();
int index = 0;
for (int i = 0; i < 5; i++,index++)
{
//一些label初始设置
labels[i] = new Label();
labels[i].AutoSize = false;
labels[i].BackColor = Color.Orange;
labels[i].Font = new Font("微软雅黑", 15F, FontStyle.Bold, GraphicsUnit.Point, 134);
labels[i].Margin = new Padding(5, 0, 5, 0);
labels[i].Size = new Size(121, 69);
labels[i].BringToFront();
labels[i].TextAlign = ContentAlignment.MiddleCenter;
la.Add(labels[i]);
panel1.Controls.Add(la[i]);
switch (index)
{
case 0:
labels[i].Text = "11";
labels[i].Name = "11";
labels[i].Location = new Point(13 + 130 * i,15); break;
case 1:
labels[i].Text = "12";
labels[i].Name = "12";
labels[i].Location = new Point(13 + 130 * i, 15); break;
case 2:
labels[i].Text = "13";
labels[i].Name = "13";
labels[i].Location = new Point(13 + 130 * i, 15); break;
case 3:
labels[i].Text = "14";
labels[i].Name = "14";
labels[i].Location = new Point(13 + 130 * i, 15); break;
case 4:
labels[i].Text = "15";
labels[i].Name = "15";
labels[i].Location = new Point(13 + 130 * i, 15); break;
default: break;
}
}
Dictionary<Label, double> dic1 = new Dictionary<Label, double>();
dic1.Add(labels[0], 0.001);//11 12 [1] //[]内为原排列i的下标
dic1.Add(labels[1], 0.220);//12 15 [4]
dic1.Add(labels[2], 0.002);//13 14 [3]
dic1.Add(labels[3], 0.033);//14 13 [2]
dic1.Add(labels[4], 0.100);//15 11 [0]
//根据value进行排序
var sortResult1 = (from pair in dic1 orderby pair.Value descending select pair).ToDictionary(pair => pair.Key, pair => pair.Value);
for (int i = 0; i < 5; i++)
{
panel2.Controls.Add(sortResult1.ElementAt(i).Key);
sortResult1.ElementAt(i).Key.Location = new Point(13 + 130 * i, 15);
}
}
}
}