How to access random item in list?

后端 未结 12 1083
滥情空心
滥情空心 2020-11-22 15:20

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

12条回答
  •  悲&欢浪女
    2020-11-22 15:51

    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]);
      

提交回复
热议问题