关键值匹配

时间:2018-06-12 22:02:28

标签: c# winforms

enter image description here

以上是我的gui的样子。在表单加载时,排序列表会在标签上显示三个随机选择的键。然后,用户选择相应的值以使其与密钥匹配。

这就是我正在努力的事情!下面是我走了多远。请帮助!!

private void Form1_Load(object sender, EventArgs e)
{
    //create the sorted list and add items
    SortedList<string,string> sl = new SortedList<string,string>();
    sl.Add("PicknPay", "jam");
    sl.Add("Spar", "bread");
    sl.Add("Checkers", "rice");
    sl.Add("Shoprite", "potato");
    sl.Add("Cambridge", "spinash");

    //declare random variable
    var rnd = new Random();
    var shuffledKeys = sl.Keys.OrderBy(key => rnd.Next()).ToList();

    lbl1.Text = shuffledKeys[0];
    lbl2.Text = shuffledKeys[1];
    lbl3.Text = shuffledKeys[2];
}

这就是我当前的想法如何帮助我将标签输出与组合框选择相匹配,以确认其实际上是有效的键值对

private void btnmatch_Click(object sender, EventArgs e)
{
    int count = 0;
    //match 
    if (sl.keys.Containskey(shuffledKeys[0]) || sl.value.Containsvalue(cb1.SelectedValue))
    {
        count++; //score                 
    }
    else
    {
        //Do nothing
    }        
}

1 个答案:

答案 0 :(得分:0)

下面的代码怎么样?目前尚不清楚标签中的键是否应该是唯一的。如果他们这样做,你应该再添加一个循环来选择一个唯一的随机数。

   public partial class Form1 : Form
    {
        private Label[] labels;
        private ComboBox[] combos;
        private Random r = new Random();
        SortedList<string, string> sl = new SortedList<string, string>();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            labels = new Label[]{ label1, label2, label3 };
            combos = new ComboBox[]{ comboBox1, comboBox2, comboBox3 };
            sl.Add("Key1", "Value1");
            sl.Add("Key2", "Value2");
            sl.Add("Key3", "Value3");
            sl.Add("Key4", "Value4");
            sl.Add("Key5", "Value5");

            HashSet<int> used = new HashSet<int>();

            foreach (Label l in labels)
            {
                int n = r.Next(0, sl.Count);
                while(used.Contains(n))
                   n = r.Next(0, sl.Count);
                used.Add(n);
                l.Text = sl.ElementAt(n).Key;
            }
            foreach(ComboBox combo in combos)
            {
                foreach(string s in sl.Values)
                {
                    combo.Items.Add(s);
                }
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            int nCorrect = 0;

            for(int n = 0; n < labels.Length; n++)
            {
                if(combos[n].Text == sl[labels[n].Text])
                {
                    nCorrect++;
                }

            }
            labelScore.Text = nCorrect.ToString();
        }
    }