列表中的随机访问项目 [英] Access random item in list

查看:166
本文介绍了列表中的随机访问项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ArrayList,我需要能够点击一个按钮,然后随机挑选出从该列表的字符串并显示它的一个消息。

我怎么会去这样做?


解决方案

  1. 创建随机类某处的一个实例。请注意,这是pretty重要的是不要每次需要一个随机数的时间创建一个新的实例。您应该重新使用旧实例中生成的数字,以达到均匀。你可以有一个静态字段地方(小心线程安全问题):

     静态随机RND =新的随机();


  2. 询问随机实例给你的最大的的ArrayList的项目数的随机数

      INT R = rnd.Next(list.Count);


  3. 显示字符串:

      MessageBox.Show((字符串)列表[R]);


I have an ArrayList, and I need to be able to click a button and then randomly pick out a string from that list and display it in a messagebox.

How would I go about doing this?

解决方案

  1. Create an instance of Random class somewhere. Note that it's pretty important not to create a new instance each time you need a random number. You should reuse the old instance to achieve uniformity in the generated numbers. You can have a static field somewhere (be careful about thread safety issues):

    static Random rnd = new Random();
    

  2. Ask the Random instance to give you a random number with the maximum of the number of items in the ArrayList:

    int r = rnd.Next(list.Count);
    

  3. Display the string:

    MessageBox.Show((string)list[r]);
    

这篇关于列表中的随机访问项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆