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?
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?
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 astatic
field somewhere (be careful about thread safety issues):Ask the
Random
instance to give you a random number with the maximum of the number of items in theArrayList
:Display the string:
I usually use this little collection of extension methods:
For a strongly typed list, this would allow you to write:
If all you have is an ArrayList, you can cast it:
I have been using this ExtensionMethod for a while:
Create a
Random
instance:Fetch a random string:
Remember though, that if you do this frequently you should re-use the
Random
object. Put it as a static field in the class so it's initialized only once and then access it.Printing randomly country name from JSON file.
Model:
Implementaton: