Results 1 to 25 of 25

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

    C #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(Of T) rather than an ArrayList.
    VB Code:
    1. Dim list As New ArrayList
    2.  
    3.         For i As Integer = 1 To 10
    4.             'Add the numbers to the collection.
    5.             list.Add(i)
    6.         Next i
    7.  
    8.         Dim rand As New Random
    9.         Dim index As Integer
    10.         Dim item As Object
    11.  
    12.         'Display the items in random order.
    13.         While list.Count > 0
    14.             'Choose a random index.
    15.             index = rand.Next(0, list.Count)
    16.  
    17.             'Get the item at that index.
    18.             item = list(index)
    19.  
    20.             'Remove the item so that it cannot be chosen again.
    21.             list.RemoveAt(index)
    22.  
    23.             'Display the item.
    24.             MessageBox.Show(item.ToString())
    25.         End While
    Last edited by jmcilhinney; Oct 29th, 2008 at 08:03 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