Results 1 to 1 of 1

Thread: Unique, Random Selections from a List

  1. #1

    Thread Starter
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Sydney, Australia

    Unique, Random Selections from a List

    VB version here.

    This is pretty simple stuff but it's come up more than once so I thought I'd post it. If you want to randomly select objects from a list where each object can only be chosen once you can use a collection and a Random object to select indexes into that collection. Below is an example using an ArrayList and the numbers 1 to 10. The objects could be anything though, not just numbers. In .NET 2.0 you'd more likely use a Generic.List<T> rather than an ArrayList.
    ArrayList list = new ArrayList();
    for (int i = 1; (i <= 10); i++)
        // Add the numbers to the collection.
    Random rand = new Random();
    int index;
    object item;
    // Display the items in random order.
    while ((list.Count > 0))
        // Choose a random index.
        index = rand.Next(0, list.Count);
        // Get the item at that index.
        item = list[index];
        // Remove the item so that it cannot be chosen again.
        // Display the item.
    Last edited by jmcilhinney; Oct 29th, 2008 at 08:04 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts


Click Here to Expand Forum to Full Width