【问题标题】:Put a shuffled list into a ListBox将洗牌后的列表放入 ListBox
【发布时间】:2023-12-20 05:47:01
【问题描述】:

我试图将洗牌的列表对象放入列表框中。我不知道随机发生器是否有效,这就是我想用列表框尝试它的原因。问题是“无法将 int 转换为字符串”我尝试了不同的方法来转换它,但没有任何效果......请帮助我 =)

(这样做的原因是我创建了一个需要“随机播放”按钮的内存)

private void button2_Click(object sender, EventArgs e)
{
    List<String> randomList = new List<string>();
    {
        randomList.Add(textBox1.Text);
        randomList.Add(textBox2.Text);
        randomList.Add(textBox3.Text);
        randomList.Add(textBox4.Text);
        randomList.Add(textBox5.Text);
        randomList.Add(textBox6.Text);
        randomList.Add(textBox7.Text);
        randomList.Add(textBox8.Text);
        randomList.Add(textBox9.Text);
        randomList.Add(textBox10.Text);
    }

    Random rnd = new Random();
    for (int i = 0; i < randomList.Count; i++) 
    {
        int pos = rnd.Next(i + 1);
        var x = randomList[i];
        randomList[i] = randomList[pos];
        randomList[pos] = x;
        randomList[x].add(listBox1);            
    }
}

【问题讨论】:

    标签: c# list random converter shuffle


    【解决方案1】:

    您可以编写一个扩展方法,该方法将使用 Fisher-Yates 算法进行洗牌,如下所示:

    public static class Extensions
    {
        public static void Shuffle<T>(this IList<T> list)  
        {  
            Random rnd = new Random();  
            int n = list.Count;  
            while (n > 1) {  
                n--;  
                int k = rnd.Next(n + 1);  
                T value = list[k];  
                list[k] = list[n];  
                list[n] = value;  
            }   
        }
    }
    

    然后用这个方法

    randomList.Shuffle();
    listbox1.DataSource=randomList; 
    listbox1.DataBind();
    

    有关 Fisher-Yates 算法的更多信息,请查看here

    【讨论】:

    • 谢谢克里斯托斯。但我收到错误“无法将类型 'void' 隐式转换为 'System.Collections.Generic.List
    • 请让我检查一下,我会相应地更新我的代码。
    • 如果我删除了“randomList =”并且只写了 randomList.Shuffle();我没有错误。但是之后我怎么把它放到我的“listbox1”中呢?
    • 你可以写 listbox1.DataSource=randomList.Shuffle();然后是 listbox1.DataBind();
    • 然后我得到这个错误“'System.Collections.Generic.List'不包含'Shuffle'的定义并且没有扩展方法'Shuffle'接受'System'类型的第一个参数.Collections.Generic.List' 可以找到(您是否缺少 using 指令或程序集引用?)"
    【解决方案2】:

    我不知道这条线是怎么回事

    randomList[x].add(listBox1); 有效,或者listbox1 来自哪里

    randomList is a string list and you trying to add listBox1 which won't work
    

    但是要重新排序列表,您可以简单地做

    var rand = new Random();
    randomList = randomList.OrderBy(l => rand .Next()).ToList();
    

    【讨论】: