我试图随机列出一个列表,然后将其放入图片框。当我这样做时,我收到错误消息“索引超出范围。必须为非负数,并且小于集合的大小”
这是随机代码:
public class Dealer
{
public static Random rand = new Random();
public static List<Kort> KortenÄrBlandade = new List<Kort>();
public void Shuffle()
{
List<Kort> KortenÄrBlandade = new List<Kort>(deckOfCards.OrderBy(_ => rand.Next(0, deckOfCards.Count)));
}
}
这是调用该方法的代码
private void button1_Click(object sender, EventArgs e)
{
Spelare.Dealer deal = new Spelare.Dealer();
deal.Shuffle();
pictureBox1.Image = Spelare.Dealer.KortenÄrBlandade[2].img;
}
最佳答案
您可以尝试使用Fisher-Yates随机播放算法
http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
可能是这样的:
public class Dealer {
// Fisher-Yates shuffle algorithm with explicit generator
private static void CoreShuffle(IList<Kort> list, Random generator) {
if (Object.ReferenceEquals(null, list))
throw new ArgumentNullException("list");
else if (Object.ReferenceEquals(null, generator))
throw new ArgumentNullException("generator");
for (int i = list.Count - 1; i >= 0; --i) {
int index = generator.Next(i + 1);
Kurt h = list[index];
list[index] = list[i];
list[i] = h;
}
}
public static Random rand = new Random(); // <- Be careful: Random is not thread safe; readonly is also a good addition here
// Return new shuffled list based on deckOfCards
public List<Kort> ShuffledList() {
List<Kort> result = new List<Kort>(deckOfCards); // <- Check this line in your code
CoreShuffle(result, rand);
return result;
}