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
I usually use this little collection of extension methods:
public static class EnumerableExtension
{
public static T PickRandom(this IEnumerable source)
{
return source.PickRandom(1).Single();
}
public static IEnumerable PickRandom(this IEnumerable source, int count)
{
return source.Shuffle().Take(count);
}
public static IEnumerable Shuffle(this IEnumerable source)
{
return source.OrderBy(x => Guid.NewGuid());
}
}
For a strongly typed list, this would allow you to write:
var strings = new List();
var randomString = strings.PickRandom();
If all you have is an ArrayList, you can cast it:
var strings = myArrayList.Cast();