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
Or simple extension class like this:
public static class CollectionExtension
{
private static Random rng = new Random();
public static T RandomElement(this IList list)
{
return list[rng.Next(list.Count)];
}
public static T RandomElement(this T[] array)
{
return array[rng.Next(array.Length)];
}
}
Then just call:
myList.RandomElement();
Works for arrays as well.
I would avoid calling OrderBy() as it can be expensive for larger collections. Use indexed collections like List or arrays for this purpose.