将一个混洗列表放入ListBox

时间:2014-04-29 09:46:09

标签: c# list random converter shuffle

我试图将混洗后的列表对象放入列表框中。我不知道随机数发生器是否工作,这就是为什么我想用列表框来尝试它。问题是“无法将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);            
    }
}

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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

相关问题