我目前正在为M.U.G.E.N的锦标赛经理工作。它从SQL Server数据表中读取战斗机并将行存储在ListBox中。它也应该随机挑选16名战士。
我已经创建了一个随机生成器和一个HashSet - 以防止任何重复 - 在while循环中,所以这个过程只在16个战士被挑选时停止。这是我到目前为止所写的:
private void buttonRandom_Click(object sender, EventArgs e)
/*
* Randomly pick 16 fighters from the "Registered" ListBox
* Only unique IDs are allowed
*/
{
Random contestantPicker = new Random();
HashSet<int> fighters = new HashSet<int>();
while (fighters.Count < 16) // Run Random until 16 fighters have been picked
{
fighters.Add(contestantPicker.Next(0, listBoxRegistered.Items.Count));
}
}
现在的问题是:如何使用存储在HashSet中的数字将具有相应索引的项目从一个ListBox复制到另一个ListBox?
答案 0 :(得分:0)
生成HashSet
后,迭代它并按索引查找相应的项目。
像这样:
//old code
Random contestantPicker = new Random();
HashSet<int> fighters = new HashSet<int>();
while (fighters.Count < 16) // Run Random until 16 fighters have been picked
{
fighters.Add(contestantPicker.Next(0, listBoxRegistered.Items.Count));
}
//list to hold fighter names
List<string> fightersList = new List<string>();
//iterate through all indexes in hashset
for (int i = 0; i < fighters.Count; i++)
{
//show in output window
Diagnostics.Debug.WriteLine("figther number {0}, named: {1}", i + 1, listBoxRegistered.GetItemText(listBoxRegistered.Items[fighters.ElementAt(i)]));
//add fighters to list...
fightersList.Add(listBoxRegistered.GetItemText(listBoxRegistered.Items[fighters.ElementAt(i)]));
}
//... and show it in some message box
MessageBox.Show(string.Join(", ", fightersList.ToArray()));