Results 1 to 1 of 1

Thread: Unique, Random Selections from a List

Threaded View

  1. #1

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    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.
    Code:
    ArrayList list = new ArrayList();
    
    for (int i = 1; (i <= 10); i++)
    {
        // Add the numbers to the collection.
        list.Add(i);
    }
    
    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.
        list.RemoveAt(index);
    
        // Display the item.
        MessageBox.Show(item.ToString());
    }
    Last edited by jmcilhinney; Oct 29th, 2008 at 08:04 PM.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

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