Problem
I have an ArrayList, and I need to be able to press a button, then pick a string at random from the list and show it in a messagebox.
What would be the best way for me to go about it?
Asked by jay_t55
Solution #1
Answered by mmx
Solution #2
This small selection of extension techniques is what I generally use:
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());
}
}
This would allow you to write: for a strongly typed list:
var strings = new List<string>();
var randomString = strings.PickRandom();
You can cast an ArrayList if that is all you have:
var strings = myArrayList.Cast<string>();
Answered by Mark Seemann
Solution #3
You can do:
list.OrderBy(x => Guid.NewGuid()).FirstOrDefault()
Answered by Felipe Pessoto
Solution #4
Alternatively, you could use a basic extension class like this:
public static class CollectionExtension
{
private static Random rng = new Random();
public static T RandomElement<T>(this IList<T> list)
{
return list[rng.Next(list.Count)];
}
public static T RandomElement<T>(this T[] array)
{
return array[rng.Next(array.Length)];
}
}
Then just call:
myList.RandomElement();
It’ll also work with arrays.
I would avoid using OrderBy() because it can be costly when dealing with huge datasets. For this, use indexed collections like ListT> or arrays.
Answered by Dave_cz
Solution #5
Make a haphazard instance of yourself:
Random rnd = new Random();
To get a random string, perform the following:
string s = arraylist[rnd.Next(arraylist.Count)];
Keep in mind that if you’re going to do this a lot, you should reuse the Random object. Put it in the class as a static field so it’s only initialized once and then accessed.
Answered by Joey
Post is based on https://stackoverflow.com/questions/2019417/how-to-access-random-item-in-list