In order to get a random item from a List instance, you need to generate a random index number and then fetch an item by this generated index number using List. get() method.
In Python, you can randomly sample elements from a list with choice() , sample() , and choices() of the random module. These functions can also be applied to a string and tuple. choice() returns one random element, and sample() and choices() return a list of multiple random elements.
1. Using Random#Next() Method. A simple and fairly efficient solution to select a random element from a List involves getting a random index value. The idea is to create an instance of the Random class, and generate a random index between 0 and the total number of elements in the List.
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 (be careful about thread safety issues):
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>();
You can do:
list.OrderBy(x => Guid.NewGuid()).FirstOrDefault()
Or simple 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();
Works for arrays as well.
I would avoid calling OrderBy()
as it can be expensive for larger collections. Use indexed collections like List<T>
or arrays for this purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With