Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

September 21, 2009

Randomly Pick Items From a List

Filed under: C#,VB.NET @ 5:29 pm

There are often times in most applications where you need to work with lists. You may have lists of customer types or list of settings or lists of numbers. Regardless of the type of item in your list, this post describes how to randomly pick a set of items from the list.

In this example, the code randomly picks a set of words from an array of words. But you could easily use this technique to pick items from any list or array of any strings, numbers, or objects.

In C#:

string myText = "That that is, is. That that is not, is not. " +
                                          "Is that it? It is.";
string[] wordArray = myText.Split(‘ ‘);

// Random instance
Random rnd = new Random();

int numberOfNumbers = 6;
List<int> randomNumbers = new List<int>();
int numberCount = 0;
do
{
    int randomNumber;
    randomNumber = rnd.Next(0, wordArray.Length);

    // Ensure this random number was not already selected
    if (!randomNumbers.Contains(randomNumber))
    {
        randomNumbers.Add(randomNumber);
        numberCount += 1;
    }
} while (numberCount < numberOfNumbers);

// Display the randomly selected words
foreach (var randomNumber in randomNumbers)
{
    Debug.WriteLine(wordArray[randomNumber]);
}

In VB:

Dim myText As String="That that is, is. That that is not, is not. " & _
                                               "Is that it? It is."
Dim wordArray() As String = myText.Split(" "c)

‘ Random instance
Dim rnd As New Random()

Dim numberOfNumbers As Integer = 6
Dim randomNumbers As New List(Of Integer)
Dim numberCount = 0
Do
    Dim randomNumber As Integer
    randomNumber = rnd.Next(0, wordArray.Length)

    ‘ Ensure this random number was not already selected
    If (Not randomNumbers.Contains(randomNumber)) Then
        randomNumbers.Add(randomNumber)
        numberCount += 1
    End If
Loop While (numberCount < numberOfNumbers)

‘ Display the randomly selected words
For Each randomNumber In randomNumbers
    Debug.WriteLine(wordArray(randomNumber))
Next

In both examples, the first two lines of code puts the words from the string into an array. This was just an easy way to build a quick array of data.

Note: If you want more information on how the Split function works, see this post.

The code then creates an instance of the Random class. The code uses this instance to generate the random numbers.

The numberOfNumbers variable defines the number of desired random numbers. In this case, I picked 6. You could set this to any value.

The randomNumbers variable is a generic list that contains the selected list of random numbers. So as the code selects the (6 in this case) random numbers, they will be added to this list.

The numberCount variable counts how many random numbers that have been selected.

The code then performs a Do loop, repeating the next set of code until the desired number of random numbers were selected.

This code cannot simply loop a defined number of times to select the defined number of random numbers. In this case, for example, it could not simply loop six times. That is because the Random function picks "with replacement", meaning that it can pick the same number multiple times.

Note: If you do want to allow random selection "with replacement", meaning that the same item can be picked from the list multiple times, then you can just loop for the defined number of times and you don’t need the if statement that checks whether the random number was already picked.

Within the loop, the Next method of the Random object is used to pick a number between 0 (inclusive) and the length of the array (exclusive). Basically, since the wordArray has a length of 15 in this example, this picks random numbers between 0 and 14.

If the random number is not already in the randomNumbers list, the code adds it to the list and loops again. If the random number is in the list, it just loops to pick another number.

When the appropriate number of random numbers are obtained, the random numbers are used to access the list items. In this case, it displays the array item.

For example, on one run through of this code, the output is:

not,
not.
is
Is
is,
it?

On a second run through, the output is:

That
That
is.
not.
that
is,

Use this technique any time you want to retrieve a random set of items from a list (array or generic list).

Enjoy!

1 Comment

  1.   Arielr — September 23, 2009 @ 4:37 pm    Reply

    yourList.OrderBy(x=>Guid.NewGuid()).Take(numberOfItems);

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2019 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs