You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WinForm将字典键值无重复添加到两个ListBox实现列匹配功能

实现思路
  • 先声明全局Random实例,避免短时间多次随机生成重复值
  • 先从字典中抽取3组不重复的键值对,将键绑定到第一个ListBox,同时保留对应的值
  • 从字典剩余未选中的条目中抽取4个不重复的值
  • 将3个匹配值与4个随机值打乱顺序后绑定到第二个ListBox
完整实现代码

假设你的两个ListBox控件名称分别为listBox1(放键)、listBox2(放值),完整代码如下:

// 全局Random实例,放在Form类里,不要放在方法内
private Random random = new Random();
// 存储选中的3组匹配键值对,方便后续做匹配校验用
private List<KeyValuePair<string, string>> selectedPairs = new List<KeyValuePair<string, string>>();

private void Form1_Load(object sender, EventArgs e)
{
    Dictionary<string, string> callingNumbers = new Dictionary<string, string>();
    callingNumbers.Add("000", "Computer science, information & general works");
    callingNumbers.Add("100", "Philosophy & psychology");
    callingNumbers.Add("200", "Religion");
    callingNumbers.Add("300", "Social sciences");
    callingNumbers.Add("400", "Language");
    callingNumbers.Add("500", "Science");
    callingNumbers.Add("600", "Technology");
    callingNumbers.Add("700", "Arts & recreation");
    callingNumbers.Add("800", "Literature");
    callingNumbers.Add("900", "History & geography");

    // 1. 随机取3个不重复的键值对
    selectedPairs = callingNumbers.OrderBy(x => random.Next()).Take(3).ToList();
    // 把键绑定到第一个ListBox
    listBox1.Items.Clear();
    listBox1.Items.AddRange(selectedPairs.Select(p => p.Key).ToArray());

    // 2. 取剩下没被选中的7个值,随机挑4个
    var unselectedValues = callingNumbers.Where(p => !selectedPairs.Any(sp => sp.Key == p.Key))
                                        .Select(p => p.Value)
                                        .OrderBy(x => random.Next())
                                        .Take(4)
                                        .ToList();

    // 3. 合并3个匹配值和4个随机值,打乱顺序后绑定到第二个ListBox
    var allValues = selectedPairs.Select(p => p.Value).Concat(unselectedValues)
                                .OrderBy(x => random.Next())
                                .ToArray();
    listBox2.Items.Clear();
    listBox2.Items.AddRange(allValues);
}
注意事项
  • Random实例要声明为窗体类的全局成员,不要写在Form1_Load方法内,否则短时间多次调用会生成重复随机值
  • 保留的selectedPairs列表可以后续用来做匹配校验,比如用户选中某个键和某个值时,判断是否匹配
  • 所有值都做了去重处理,不会出现重复值的情况

内容的提问来源于stack exchange,提问作者Sudhir Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:54:03