views:

213

answers:

5

Hi All,

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 doing this? Any help at all is greatly appreciated.

Thank you

Bael

+1  A: 

Create a Random instance:

Random rnd = new Random();

Fetch a random string:

string s = arraylist[rnd.Next(arraylist.Length)];

Remember though, that if you do this frequently you should re-use the Random object. Put it as a static field in the class so it's initialized only once and then access it.

Joey
+1  A: 

You want to adapt that and store the random instance somewhere. The concept is:

var itemToShow = yourList[new Random().Next(yourList.Count-1)];
Benjamin Podszun
If it's a frequent selection I'd move the `new Random()` into a variable and only create it the once.
ChrisF
`new Random().Next(...)` is almost always the wrong way to approach the problem (read the first point in my answer). Besides, the argument to `Next` is **exclusive** upper bound. You shouldn't subtract one from it.
Mehrdad Afshari
+5  A: 
  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:

    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]);
    
Mehrdad Afshari
thank you very much Mehrdad Afshari. Very quick and easy solution, much appreciated. :D
baeltazor
+1  A: 

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>();
Mark Seemann
+1  A: 

You can do:

list.OrderBy(x => Guid.Newid()).FirstOrDefault()
Fujiy