How to access random item in list? How to access random item in list? arrays arrays

How to access random item in list?


  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 (be careful about thread safety issues):

    static Random rnd = new Random();
  2. 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);
  3. 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()