Hi All,
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? Any help at all is greatly appreciated.
Thank you
Bael
Hi All,
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? Any help at all is greatly appreciated.
Thank you
Bael
Create a Random
instance:
Random rnd = new Random();
Fetch a random string:
string s = arraylist[rnd.Next(arraylist.Length)];
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.
You want to adapt that and store the random instance somewhere. The concept is:
var itemToShow = yourList[new Random().Next(yourList.Count-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:
static Random rnd = new Random();
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);
Display the string:
MessageBox.Show((string)list[r]);
I usually use this little collection of extension methods:
public static class EnumerableExtension
{
public static T PickRandom<T>(this IEnumerable<T> source)
{
return source.PickRandom(1).Single();
}
public static IEnumerable<T> PickRandom<T>(this IEnumerable<T> source, int count)
{
return source.Shuffle().Take(count);
}
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
{
return source.OrderBy(x => Guid.NewGuid());
}
}
For a strongly typed list, this would allow you to write:
var strings = new List<string>();
var randomString = strings.PickRandom();
If all you have is an ArrayList, you can cast it:
var strings = myArrayList.Cast<string>();